1,非空约束 not null
2,唯一约束 unique
3,主键约束 primary key
4,默认约束 default
5,检查约束 check
6,外键约束 foreign key
create table users (
id int primary key auto_increment comment '主键',
name varchar(10) not null comment '姓名',
gender char(1) not null comment '性别',
status char(1) default '1' comment '状态',
age int check(age>0 && age<120) comment '年龄'
)comment '信息表';
外界约束有子表和父表
创建父表:
create table dept(
id int auto_increment comment 'ID' primary key,
name varchar(50) not null comment '部门名称'
)comment '部门表';
INSERT INTO dept (id, name) VALUES (1, '研发部'), (2, '市场部'),(3, '财务部'), (4,
'销售部'), (5, '总经办');
创建子表:
create table emp_new(
id int auto_increment comment 'ID' primary key,
name varchar(50) not null comment '姓名',
age int comment '年龄',
job varchar(20) comment '职位',
salary int comment '薪资',
entrydate date comment '入职时间',
managerid int comment '直属领导ID',
dept_id int comment '部门ID'
)comment '员工表';
iNSERT INTO emp_new (id, name, age, job,salary, entrydate, managerid, dept_id)
VALUES
(1, '金庸', 66, '总裁',20000, '2000-01-01', null,5),(2, '张无忌', 20,
'项目经理',12500, '2005-12-05', 1,1),
(3, '杨逍', 33, '开发', 8400,'2000-11-03', 2,1),(4, '韦一笑', 48, '开
发',11000, '2002-02-05', 2,1),
(5, '常遇春', 43, '开发',10500, '2004-09-07', 3,1),(6, '小昭', 19, '程
序员鼓励师',6600, '2004-10-12', 2,1);
让子表中的部门id与父表的部门id联系起来
alter table emp_new add constraint fk foreign key (dept_id)
references dept(id);
alter table emp_new drop foreign key fk;#删除外键
删除/更新行为
NO ACTION :当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不 允许删除/更新。 (与 RESTRICT 一致) 默认行为
RESTRICT:当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有则不 允许删除/更新。 (与 NO ACTION 一致) 默认行为
CASCADE:当在父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有,则 也删除/更新外键在子表中的记录。
SET NULL:当在父表中删除对应记录时,首先检查该记录是否有对应外键,如果有则设置子表 中该外键值为null(这就要求该外键允许取null)。
SET DEFAULT:父表有变更时,子表将外键列设置成一个默认的值 (Innodb不支持)
使用方法:
alter table emp_new add constraint fk foreign key (dept_id)
references dept(id) on update cascade on delete set null;