Mysql多表关系练习笔记

Mysql多表关系
关系分类:

一对多/多对一:

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

    实现方式:多对多关系的实现需要借助第三张中间表,中间表至少包含两个字段。其中每一个字段分别指向原表

  2. 一对一:

    实现方式:在任意一方建立外键,指向另一方的主键。

案例分析:旅游线路

SQL多表关系案例
代码实现:

/*
 rid 线路id
 cid 用户id
 */
#创建topic分类表
create table topic(
    cid int,
    name varchar(20)
);
#创建路线表routes
create table routes(
    rid int,
    name varchar(20),
    price int
);
#创建用户表users
create table users(
    uid int,
    username varchar(20),
    sex varchar(1) default '男',
    phone_number varchar(11)
);
#分别设置rid、cid和uid为主键
alter table routes modify rid int primary key ;
alter table topic modify cid int primary key ;
alter table users modify uid int primary key ;
#添加在路线表中添加外键cid
alter table routes add cid int;
alter table routes add constraint cid_rid
foreign key (cid) references topic(cid) on update cascade on delete cascade ;

#创建临时表t
create table t(
    rid int,
    date date,
    uid int
);

# 在表t中添加联级操作
alter table t add constraint uid
foreign key (uid) references users(uid) on update cascade on delete cascade ;
alter table t add constraint rid
foreign key (rid) references routes(rid) on update cascade on DELETE cascade ;

有关MySql约束概念,请查看《Mysql约束笔记》。
原文请查看林克的编程小记-mysql多表关系笔记

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

yrian.c

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值