MySQLStudy——外键

不建立外键的情况下遇到的问题

1. 数据重复

2. 如果 部门过长的话, 太占用空间

解决方法

重新设计一张表, 这张表 中存放部门的相关信息


部门表

create table department (
id int auto_increment primary key, 
depart_name varchar(32) not null default ''
)engine=Innodb charset=utf8;

insert into department (depart_name) values ('公关'), ('关关'),('关公');

create table userinfo (    
id int auto_increment primary key, 
name varchar(32) not null default '',
depart_id int not null default 1,

# constraint 外键名(fk_userinfo_depart) foreign key (列名(depart_id)) references 表名(department)(关联的列名(id)),
constraint fk_userinfo_depart foreign key (depart_id) references department(id)

)engine=Innodb charset=utf8;


insert into userinfo (name, depart_id) values ('root1', 1);
insert into userinfo (name, depart_id) values ('root2', 2); 错误的

注意:

创建多个外键的时候, 名称不能一样

=====> 一对多

 

外键的变种

唯一索引

create table t5(
id int,
num int,
unique(num)
)engine=Innodb charset=utf8;

作用:    
num列的值不能重复
加速查找

联合唯一索引

create table t6(
id int,
num int,
unique(id, num)
)engine=Innodb charset=utf8;

联合唯一索引作用:    
num列和id列的值不能重复
加速查找

create table t6(
id int,
num int,
unique(id, num......)
)engine=Innodb charset=utf8;

关系模型

一对多

部门表:
id depart_name
1 公关部
2 公共部
3 保安部

员工表:
id name age depart_id(外键)
1 lxxx 12 2
2 xxxx 13 1
3 xxxx 13 2

一对一

用户表:
id name age 
1 zekai 23 
2 eagon 34
3 lxxx 45
4 owen 83

博客表:
id url user_id (外键 + 唯一约束)
1 /linhaifeng 2
2 /zekai    1
3 /lxxx 3
4 /lxxx 4

多对多

用户表:
id    name    phone 
1    root1    1234
2    root2    1235
3    root3    1236
4    root4    1237
5    root5    1238
6    root6    1239
7    root7    1240
8    root8    1241

主机表:

id    hostname    
1    c1.com    
2    c2.com    
3    c3.com    
4    c4.com    
5    c5.com


为了方便查询, 用户下面有多少台主机以及某一个主机上有多少个用户, 我们需要新建第三张表:
user2host:

id    userid    hostid
1    1    1
2    1    2
3    1    3
4    2    4
5    2    5
6    3    2
7    3    4    
创建的时候, userid 和 hostid 必须是外键, 然后联合唯一索引 unique(userid, hostid)

Django orm 也会设计
posted @ 2019-06-17 16:43  挺锅锅  阅读(166)  评论(0编辑  收藏  举报