约束
大约 2 分钟约 618 字
约束 | 特点 | |
---|---|---|
主键约束 | 唯一+非空 | primary key |
唯一约束 | 唯一 | |
非空约束 | 不能为bull | |
默认值约束 | 没有指定具体数据时会给默认值 |
主键约束
设定表中某一字段为主键,那该字段所在列的数据就能够唯一的标识表中的每一行数据(作用)。设定为主键的字段一版和业务无关。有这些特点:唯一、非空、非业务相关
创建主键
create table student2
(
id int primary key,
name varchar(20)
)
添加主键
alter table test2.student2 add primary key (id)
删除主键
alter table test2.student2 drop primary key
主键自增
create table student
(
id int primary key auto_increment,
name varchar(20)
)
唯一约束
被唯一约束的字段,本列数据不允许出现重复数据,null除外,null可以出现多个
创建唯一约束
create table student
(
id int primary key auto_increment,
name varchar(20) unique
)
添加唯一约束
alter table student add unique(name)
非空约束
被非空约束的字段,本列数据不允许出现null(即空)数据。插入数据如果该字段为空将会报错。
创建非空约束
create table student
(
id int primary key auto_increment,
name varchar(20) unique not null
)
默认值约束
被默认值约束的字段,相当于给字段添加默认值,插入数据时如果字段没有被赋值,则使用默认值。
创建默认值约束
create table student
(
id int primary key auto_increment,
name varchar(20) unique not null,
address varchar(100) default '广州'
)
外键约束
外键就是从表中设定一个字段,用来保存主表中的主键值。外键约束了从表的外键值只能是主表的主键值。
添加外键约束
create table student
(
外键字段名 int,
constraint 外键名 foreign key(当前表外键字段名) references 主表名(主表主键)
)
修改字段为外键
alter table 表名 add constraint 外键名 foreign key(当前表外键字段名) references 主表(主表主键)
删除外键约束
alter table 表名 drop foreign key 外键名
级联更新、删除
alter table 表名 add constraint 外键名 foreign key(当前表外键字段名) references 主表(主表主键) on delete cascade on update cascade
外键约束使用细节
- 删除主表中的数据报错--先删除从表中的数据,再删除主表中的数据
- 修改主表中主键字段的数据--级联更新