字段属性
- 空值
- null, not null
- 默认值
- default
- 需要在创建表时指定default才能使用
- 自动增长
- auto_increment
- 从1开始,每次加1,适合为记录生成唯一的id
- 使用auto_increment必须是主键
- 使用null默认增长
- 自动增长的数据被删除,默认该编号不再被使用
- 主键
- primary key
- 一张表只能有一个主键
- 创建组合主键:
primary key(字段1, 字段2)
- 特性:非空、唯一
- 修改表添加主键:
- 方法1: alter table 表名 add primary key 字段名;
- 方法2:alter table表名 change 旧字段名 新字段名 新类型 primary key
- 作用:保证数据完整性
- 作用:加快查询速度
- 主键创建原则:
-1. 选择一个字段做主键
-2. 选择数值类型
-3. 选择改动较少的列做主键
- 唯一键
- unique
- 可以为空,一张表可以有多个唯一键
- 删除唯一键比较特别:
alter table t1 drop index id;
- 键名默认是字段名
- 为键名取名字:
create table t1(id int, name varchar(20), unique UQ_name(name));
- 查看唯一键:
show create table t1\G
- 删除唯一键:
alter table t1 drop index UQ_name;
- 外键
- 创建表添加外键:
create table 9t2(t2id int, foreign key(t2id) references t1(t1id));
- 修改表添加外键的用法:
alter table t2 add foreign key(t2id) references t1(t1id)
- 删除外键约束:
alter table 从表名 drop foreign key 外键名
- 主表中有的数据,从表才能添加
- 从表有的数据,主表必须包含
- 插入数据时,先添加主表,再添加从表
- 删除应先删从表,再删主表
- 置空操作和级联操作:
create table 9t2(t2id int, foreign key(t2id) references t1(t1id) on delete set null on update cascade);
-
comment
-
SQL注释
- 单行注释:–空格或#
- 多行注释:/* */