完整性约束

时间:2019-10-22
本文章向大家介绍完整性约束,主要包括完整性约束使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

完整性约束foreign key

即:多张进行关联的表,其中有关联的表删除操作的时候,其他的表会自动进行删除相关联的记录

这里有一个坑:select 查看出来的表的默认排序顺序是随机排序,并不是升序,最好查询的时候加上order

select * from t1 order by id desc; #desc 为降序   asc为升序

1.多对一 :多的那一个表要设置foreign key,一对一与多对一是一样的

#下面的代码是一个类型为 多对一 的一个小练习
create database one;
use one;
# 创建一个部门表
create table del(id int primary key auto_increment,name char(30));
insert into del(name) values('财务部'),('IT部'),('爱拼才会赢部');
#创建一个员工表进行关联
create table staff(id int primary key auto_increment,name char(10) not null,
                   del_id not null unique,
                   constraint fk_del foreign key(del_id) 
                   references del(id) 
                   on delete cascade 
                   on update cascade);
#插入信息                   
insert into staff(name,del_id) values('哪吒',3),('李云龙',3),('铁蛋',2);

2.多对多:新建立一个表将要联系起来的表的id进行加入即可

#多对多练习  有两张表是多对多形式的就需要再新建一张表进行联合起来
create database book1;
use book1;
#创建一个作者表
create table author(id int primary key auto_increment,name char(30) not null );
insert into author(name) values('郭德纲'),
('灰太狼'),
('猪扒皮'),
('瞎扯淡');
#创建一个书籍表
create table book(id int primary key auto_increment,name char(30) not null);
insert into book(name) values('九阳神功',1),
 ('九阴真经',2),
('九阴白骨爪',2),
('独孤九剑',3),
('降龙十巴掌',2),
('葵花宝典',3);

#创建一个联合表
create table t1(id int primary key auto_increment,
                author_id int not null,book_id int not null,
                constraint fk_book foreign key(author_id) references author(id) 
                on delete cascade     # 这里是同步删除
                on update cascade,    # 同步更新
                constraint fk_author foreign key(book_id) references book(id) 
                on delete cascade 
                on update cascade);
insert into t1(author_id,book_id) values(1,1),
(1,2),
(1,3),
(1,4),
(1,5),
(1,6),
(2,1),
(2,6),
(3,4),
(3,5),
(3,6),
(4,1)
;
select * from author order by id asc;
select * from book order by id asc;
select * from t1 order by id asc;

原文地址:https://www.cnblogs.com/whileke/p/11718454.html