数据库和表的基本操作
查看数据表
1、show create table 表名;
2、desc 表名;(或 describe 表名)
修改数据表
1、修改表名
alter table 旧表名 rename [to] 新表名;
2、修改字段名 (数据类型不能为空, 也可用于修改数据类型)
alter table 表名 change 旧字段名 新字段名 新数据类型;
3、修改字段的数据类型
alter table 表名 modify 字段名 数据类型;
4、添加字段
alter table 表名 add 新字段名 数据类型 [约束条件] [first|after 已存在的字段名];
5、删除字段
alter table 表名 drop 字段名;
6、修改字段的排列位置
alter table 表名 modify 字段名1 数据类型 first|after 字段名2;
删除数据表
drop database 表名;
表的约束
主键约束(一个表只能有一个 ,通过primary key 定义,它可以唯一标识表中的记录)
1、单字段主键
字段名 数据类型 primary key
2、多字段主键(在创建表最后面加)
primary key (字段名1,字段名2,···,字段名n)
非空约束(字段值不能为null)
字段名 数据类型 not null;
唯一约束(保证数据表字段的唯一性,即表中字段的值不能重复出现)
字段名 数据类型 unique;
默认约束(给数据表的字段指定默认值)
字段名 数据类型 default 默认值;
设置表的字段值的自动增加 (适用于任何类型的整数,必须在主键的字段上)
字段名 数据类型 auto_increment;
索引(以此来加快数据表的查询和排序)
1、普通索引:key index
2、唯一索引:unique
3、全文索引:fulltext (只能创建在char、varchar 或 text 类型的字段上)
4、单列索引
5、多列索引
6、空间索引:spatial (只能建立在空间数据类型的字段上,创建空间索引的字段上必须将其声明为not null)
1、创建索引 (在创建表的基础上)
create table 表名 (字段名 数据类型 [完整性约束条件]) ,
(字段名 数据类型 [完整性约束条件])
···
字段名 数据类型
[unique|fulltext|spatial|index|key]
[别名] (字段名1[(长度)] [asc|desc])
);
查询创建的索引用explain
explain select ··········
2、使用create index 语句在已经存在的表上创建索引
create [unique|fulltext|spatial] index 索引名 on 表名 (字段名[(长度)] [asc|desc]);
3、使用alter table 语句在已经存在的表上创建索引
alter table 表名 add [unique|fulltext|spatial] index 索引名 (字段名 [(长度)] [asc|desc]);
删除索引
1、使用alter table 删除
alter table 表名 drop index 索引名;
2、使用drop index 删除
drop index 索引名 on 表名;

浙公网安备 33010602011771号