1.约束
1.1 约束概述
(1)概念
对表中的数据进行限定,保证数据的正确性、有效性和完整性。
(2)分类
- 非空约束:not null,值不能为空。
- 唯一约束:unique,值不能重复(唯一)。
- 主键约束:primary key,值非空且唯一。
- 外键约束:foreign key,让表与表产生关系,从而保证数据的正确性。
1.2 非空约束
(1)创建表时,添加条件约束
create table 表名(
字段名 字段类型 not null,
...
);
(2)创建表后,添加非空约束
alter table 表名 modify 字段名 字段类型 not null;
(3)删除非空约束
alter table 表名 modify 字段名 字段类型;
1.3 唯一约束
(1)创建表时,添加唯一约束
create table 表名(
字段名 字段类型 unique,
...
);
(2)创建表后,添加唯一约束
alter table 表名 drop index 字段名;
(3)删除唯一约束
alter table 表名 modify 字段名 字段类型 unique;
1.4 主键约束
(1)注意
- 含义:非空且唯一(not null and unique)
- 一张表只能有一个字段为主键
- 主键就是表中记录的唯一标识
(2)创建表时,添加主键约束
create table 表名(
字段名 字段类型 primary key,
...
);
(3)删除主键
alter table 表名 drop primary key 字段名;
(4)创建表后,添加主键约束
alter table 表名 modify 字段名 字段类型 primary key;
(5)自动增长
- 概念:如果某一列是数值类型的值,使用 auto_increment 可以来完成值的自动增长。
- 在创建表时,添加主键约束,并完成主键的自动增长
create table 表名(
字段名 字段类型 primary key auto_increment,
...
);
- 删除自动增长
alter table 表名 modify 字段名 字段类型;
- 创建表后,添加自动增长
alter table 表名 modify 字段名 字段类型 auto_increment;
1.5 外键约束
(1)创建表时,添加外键
create table 表名(
...
外键列
constraint 外键名称 foreign key (外键列名) references 主表名称 (主表列名称)
);
(2)删除外键
alter table 表名 drop foreign key 外键列名;
(3)创建表后,添加外键
alter table 表名 add constraint 外键名称 foreign key (外键列名) references 主表名称(主表列名称);
- 注意:外键列的值可以为null,但是不能为不存在的外键值。
1.6 级联操作
(1)创建表后,添加外键,并设置级联更新
- 级联更新也就是 当修改了外键关联的表的某个字段值后,当前表中有关数据也同时改变。
alter table 表名 add constraint 外键名称 foreign key (外键列名称) references 主表名称(主表列名称) on update cascade;
(2)创建表后,添加外键,并设置级联删除
- 级联删除也就是 当删除了外键关联的表的某行数据后,当前表中有关数据也会同时被删除。
- 级联更新和级联删除可以同时设置。
alter table 表名 add constraint 外键名称 foreign key (外键列名称) references 主表名称(主表列名称) on delete cascade;