1.主键约束
primary key
2.非空
not null
3.唯一约束
unique
4.自增加
auto_increment
5.检查约束
check()
6.默认约束
default
7.外键盘约束 (保证数据的完整性和一致性)
foreign key
create table home
(
home_id int primary key comment '家庭编号,主键',
home_num int not null comment '家庭成员数量',
home_master_id int comment '户主名'
)comment '家庭表';
alter table home add position varchar(20);
select * from home;
insert into home values(1,19,1,'匈奴家');
insert into home values(2,19,1,'波斯家');
insert into home values(3,19,1,'蒙古家');
insert into home values(4,19,1,'吐蕃家');
insert into home values(5,19,1,'铁勒家');
select * from home;
create table user
(
u_id int primary key auto_increment comment '主键约束,自增',
u_name varchar(20) unique comment '用户名,唯一约束',
u_age int check(u_age >=0 and u_age <= 120) comment '年龄,check约束',
u_sex char(1) default '男' comment '性别,默认约束',
u_online char(10) default 'online' comment '是否在线 默认约束',
home_id int,
constraint fk_home_id foreign key(home_id) references home(home_id)
)comment '用户表';
select * from user;
show databases;
select database();
insert into user values(1,'单于',20,'男','online',1);
insert into user values(2,'可汗',25,'男','online',2);
insert into user values(3,'天子',50,'男','online',3);
insert into user values(4,'大头领',33,'男','online',4);
select * from user join home on user.home_id = home.home_id;
外键有两种创建方法
1.在创建表的时候直接创建好
【constraint】 【外键名】 foreign key(字段名) references 主表(主表列名)
2.在表创建后,再单独创建外键
alter table 表名 add constraint 外键名称 foreign key (外键字段名) references 主表(主表列名)
删除外键
alter table 表名 drop foreign key 外键名;
--删除外键
alter table user drop foreign key fk_home_id;
select * from user;
select * from home;
--再次创建外键
alter table user add constraint fk_home_id foreign key (home_id) references home(home_id);
如果记录存在外键,则在删除数据时,并不能删除数据
删除和更新行为:
no action 默认行为:当在父表中删除或更新,首先检查该记录是否有对应的外键,如果有则不允许删除或更新。
restrict 同no action
set null:删除数据时,主表设置为NULl
set default:父表有变更时,子表将外键设置成一个默认值(innodb不支持此功能)
cascade:级联操作,当在父表中删除记录时,首先检查该记录是否有对应外键,如果有,则也删除或更新外键在子表中的记录
on update cascade on delete cascade
--cascade 级联设置
alter table user drop foreign key fk_home_id;
alter table user add constraint fk_home_id foreign key (home_id) references home(home_id)
on update cascade on delete cascade;
--set null 置空设置
alter table user drop foreign key fk_home_id;
alter table user add constraint fk_home_id foreign key (home_id) references home(home_id)
on update set null on delete set null;
--默认设置 不允许修改 no action 或restrict
alter table user drop foreign key fk_home_id;
alter table user add constraint fk_home_id foreign key (home_id) references home(home_id)
on update no action on delete no action;
alter table user drop foreign key fk_home_id;
alter table user add constraint fk_home_id foreign key (home_id) references home(home_id)
on update restrict on delete restrict;