MYSQL约束应用
create database if not exists DOOK charset 'utf8'; |
create table njo_op(
id int auto_increment primary key comment 'id',#主键,不为空 ,自动增长
name varchar(10) not null unique comment '名字',# 不为空 且值是这个表唯一
age int default 20 comment '年龄',
CHECK ( age<0 and age<120 ), #大于0 并且小于120
zhuantai char(2) default '没在' comment '状态',##如果没有给指定的值,默认为没有在
xb char(1) not null comment '性别'
);
insert into njo_op values
(null,'acsasc',20,'在的','男'),
(null,'a1',89,null,'女'),
(null,'a2',19,'在的','男'),
(null,'a3',15,'在的','女'),
(null,'a4',19,null,'男'),
(null,'a6',67,'在的','女'),
(null,'l9',19,'在的','男');
#不给zhuantai 传值的话 就会用默认值
insert into njo_op(id, name, age,xb) value (null,'sdf45',20,'男');
#添加外键 #将员工的部门id 和 部门表的id 关联到一起 不可以删除或修改 alter table staffer add constraint fk_staffer_dept_id foreign key (dept_id) references department(id); #取消外键 alter table staffer drop foreign key fk_staffer_dept_id; # cascade 当父表中的删除/更新对应记录时 首先检查记录是否对应的外键 子表则也 更新/或者删除 alter table staffer add constraint fk_staffer_dept_id foreign key (dept_id) references department(id) on update cascade on delete cascade ; # 子表 父表 update department set id=10 where dept_name='技术部1'; # 员工表中的的部门为1的 的改成了 部门10的 #如果删除 部门表的 部门10 对应的员工表的部门10的员工信息就会被删除