1 /*
2 唯一索引 索引:1.为了加速查找 2.限制
3 单列唯一索引:unique uql(num)
4 多列唯一索引(联合唯一):unique uql(num,id)
5
6 唯一索引 约束不能重复可以为空
7 主键 不能重复不可以为空
8
9
10 外键变种
11 外键 实现一对多
12 例子:一张用户表 一张职位表 用户职位1对多
13 外键+唯一索引 一对一
14 例子:一张用户表 一张登录表
15 因为很少的人需要登录所以另建登录表无需要将密码存入用户表节省空间
16 外键+联合唯一 多对多
17 例子:多对多不一定要联合唯一 比如:用户表 课程表 一个人可以同时上一个课程多次
18 例子:多对多需要联合唯一
19 比如:用户表 主机表 一个人可以操作多台主机
20 但是不需要将user:1 host:1此信息存储多次故设置联合唯一unique uql(user,host)
21 */
22 /* 一对一 */
23 create table userinfo(
24 id int auto_increment primary key,
25 name char(10),
26 gender char(10),
27 email varchar(64)
28 )engine=innodb default charset=utf8;
29
30 create table admin(
31 id int not null auto_increment primary key,
32 username varchar(64) not null,
33 passwd varchar(64) not null,
34 user_id int not null,
35 /* fk + 唯一索引*/
36 unique uql(user_id),
37 constraint fk_admin_userinfo foreign key (user_id) references userinfo(id)
38 )engine = innodb default charset=utf8;
39
40
41 /*多对多*/
42 create table userinfo(
43 id int auto_increment primary key,
44 name char(10),
45 gender char(10),
46 email varchar(64)
47 )engine = innodb default charset=utf8;
48
49 create table host(
50 id int auto_increment primary key,
51 hostname char(64)
52 )engine = innodb default charset=utf8;
53
54 create table user2host(
55 id int auto_increment primary key,
56 userid int not null,
57 hostid int not null,
58 /*fK + 联合唯一 */
59 unique uq_user_host(userid,hostid),
60 constraint fk_u2h_userinfo foreign key (userid) references userinfo(id),
61 constraint fk_u2h_host foreign key (hostid) references host(id)
62 )engine=innodb default charset=utf8;