外键的变种 三种关系

由于有foreign key的约束,使得两张表造成了三种了关系:mysql

  • 多对一
  • 多对多
  • 一对一

2、重点理解若是找出两张表之间的关系

1)书和出版社sql

  一对多(或多对一):一个出版社能够出版多本书。看图说话。ide

  关联方式:foreign keyurl

 

 

 

 

 

# 建立被关联表author表,以前的book表在讲多对一的关系已建立
create table author(
    id int primary key auto_increment,
    name varchar(20)
);
#这张表就存放了author表和book表的关系,即查询两者的关系查这表就能够了
create table author2book(
    id int not null unique auto_increment,
    author_id int not null,
    book_id int not null,
    constraint fk_author foreign key(author_id) references author(id)
    on delete cascade
    on update cascade,
    constraint fk_book foreign key(book_id) references book(id)
    on delete cascade
    on update cascade,
    primary key(author_id,book_id)
);

#插入四个做者,id依次排开
insert into author(name) values('小明'),('heshun'),('张三'),('李四');
# 每一个做者的表明做
小明: 九阳神功、九阴真经、九阴白骨爪、独孤九剑、降龙十巴掌、葵花宝典
heshun: 九阳神功、葵花宝典
张三:独孤九剑、降龙十巴掌、葵花宝典
李四:九阳神功

# 在author2book表中插入相应的数据

insert into author2book(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)
;
# 如今就能够查author2book对应的做者和书的关系了
mysql> select * from author2book;
+----+-----------+---------+
| id | author_id | book_id |
+----+-----------+---------+
|  1 |         1 |       1 |
|  2 |         1 |       2 |
|  3 |         1 |       3 |
|  4 |         1 |       4 |
|  5 |         1 |       5 |
|  6 |         1 |       6 |
|  7 |         2 |       1 |
|  8 |         2 |       6 |
|  9 |         3 |       4 |
| 10 |         3 |       5 |
| 11 |         3 |       6 |
| 12 |         4 |       1 |
+----+-----------+---------+
12 rows in set (0.00 sec)
做者与书籍关系(多对多)

(3)用户和博客spa

  一对一:一个用户只能注册一个博客,即一对一的关系。看图说话3d

  关联方式:foreign key+uniquecode

 

 

 

 

 

#例如: 一个用户只能注册一个博客

#两张表: 用户表 (user)和 博客表(blog)
# 建立用户表
create table user(
    id int primary key auto_increment,
    name varchar(20)
);
# 建立博客表
create table blog(
    id int primary key auto_increment,
    url varchar(100),
    user_id int unique,
    constraint fk_user foreign key(user_id) references user(id)
    on delete cascade
    on update cascade
);
#插入用户表中的记录
insert into user(name) values
('alex'),
('wusir'),
('egon'),
('xiaoma')
;
# 插入博客表的记录
insert into blog(url,user_id) values
('http://www.cnblog/alex',1),
('http://www.cnblog/wusir',2),
('http://www.cnblog/egon',3),
('http://www.cnblog/xiaoma',4)
;
# 查询wusir的博客地址
select url from blog where user_id=2;
相关文章
相关标签/搜索