表1 foreign key 表2
多对一:表 1 的多条记录对应表 2 的一条记录sql
利用foreign key的原理咱们能够制做两张表的多对多,一对一关系spa
多对多:
表1的多条记录能够对应表2的一条记录
表2的多条记录也能够对应表1的一条记录操作系统
一对一:
表1的一条记录惟一对应表2的一条记录设计
一、先确立关系code
二、找到多的一方,把关联字段写在多的一方blog
1、多对一或者一对多rem
1.先建被关联的表,保证被关联表的字段必须惟一。数学
2.在建立关联表,关联字段必定保证是要有重复的。table
一个书和出版社的一个例子,书要关联出版社(多个书能够是一个出版社,一个出版社也能够有好多书)。class
谁关联谁就是谁要按照谁的标准。
从这里看出来,书是关联者,出版社是被关联者。
书要关联出版社 被关联的表 create table press( id int primary key auto_increment, name char(20) ); 关联的表 create table book( book_id int primary key auto_increment, book_name varchar(20), book_price int, press_id int, constraint Fk_pressid_id foreign key(press_id) references press(id) on delete cascade on update cascade ); 插记录 insert into press(name) values('新华出版社'), ('海燕出版社'), ('摆渡出版社'), ('大众出版社'); insert into book(book_name,book_price,press_id) values('Python爬虫',100,1), ('Linux',80,1), ('操做系统',70,2), ('数学',50,2), ('英语',103,3), ('网页设计',22,3);
结果:
2、一对一
用户和管理员(只有管理员才能够登陆,一个管理员对应一个用户)
用户被关联
先建被关联的表 create table user( id int primary key auto_increment, #主键自增 name char(10) ); 在建关联表 create table admin( id int primary key auto_increment, user_id int unique, password varchar(16), foreign key(user_id) references user(id) on delete cascade on update cascade ); insert into user(name) values('susan1'), ('susan2'), ('susan3'), ('susan4'), ('susan5'), ('susan6'); insert into admin(user_id,password) values(4,'sds156'), (2,'531561'), (6,'f3swe');
结果:
3、多对多
书和做者(咱们能够再建立一张表,用来存book和author两张表的关系)
要把book_id和author_id设置成联合惟一
联合惟一:unique(book_id,author_id)
联合主键:alter table t1 add primary key(id,avg)
关联方式:foreign key + 一张新表
#被关联的 create table book1( id int primary key auto_increment, name varchar(10), price float(3,2) ); #========被关联的 create table author( id int primary key auto_increment, name char(5) ); #========关联的 create table author2book( id int primary key auto_increment, book_id int not null, author_id int not null, unique(book_id,author_id), foreign key(book_id) references book1(id) on delete cascade on update cascade, foreign key(author_id) references author(id) on delete cascade on update cascade ); #========插入记录 insert into book1(name,price) values('九阳神功',9.9), ('葵花宝典',9.5), ('辟邪剑谱',5), ('降龙十巴掌',7.3); insert into author(name) values('egon'),('e1'),('e2'),('e3'),('e4'); insert into author2book(book_id,author_id) values(1,1), (1,4), (2,1), (2,5), (3,2), (3,3), (3,4), (4,5);
总结:
在一对一中,unique 在关联表中