MySQL----多表操作

##多表之间的关系

1、一对一(了解)

  * 如:人和身份证

  * 分析:一个人只有一个身份证,一个身份证只能对应一个人。

2、一对多(多对一)

  * 如:部门和员工

  * 分析:一个部门有多个员工,一个员工只能对应一个部门。

3、多对多

  * 如:学生和课程

  * 分析:一个学生可以选择很多们课程,一门课程也可以被很多学生选择。

实现关系

1、一对多(多对一)

  * 如:部门和员工

  * 实现方式:在多的一方建立外键,指向一的一方的主键。

 2、多对多

  * 如:部门和员工

  * 实现方式:借助第三张中间表,至少包含两个字段,这两个字段作为第三张表的外键,分别指向两张主表的主键。

3、一对一

  * 如:人和身份证

  * 实现方式:可以在任意一方添加唯一外键指向另一方的主键。

案例:

/*旅游线路案例
  1、分类表和线路表是1 对 多的关系
  2、线路表和用户表是多对多,需要创建中间表。
  */
create table category(
    cid int primary key auto_increment,
    name varchar(64) not null unique
);
create table routes(
    rid int primary key auto_increment,
    name varchar(128) not null unique ,
    price double,
    cid int,
    /*constraint rou_cat_fk */foreign key (cid) references category(cid)
                   on delete cascade on update cascade
);
create table user(
    uid int primary key auto_increment,
    username varchar(32) not null unique ,
    password varchar(32) not null
);
create table favorite(
    rid int,
    date datetime,
    uid int,
    /*创建复合主键*/
    primary key (rid,uid),
    foreign key (rid) references routes(rid),
    foreign key (uid) references user(uid)
);
insert into category(cid, name) VALUES (1,'国外游'),(2,'国内游');
insert into routes(rid, name, price, cid) VALUES (1,'希腊游',10000.1,1),(2,'北京游',9992.1,2);
insert into user (uid, username, password)
values (null,'ftj','123'),(null,'lxy','456');
insert into favorite (rid, date, uid)
values (1,'2020-02-08 23:59:59',1),(2,'2020-02-08 23:59:59',2);
select * from user where uid = (select uid from favorite where rid = 1);
That which doesn't kill me makes me stronger!
原文地址:https://www.cnblogs.com/21seu-ftj/p/12275381.html