Mysql 的关联关系

 

                                                                                          Mysql关联关系

 

多表之间的关系是通过外键搭建的.(用户表和订单表:用户有订单,订单从属用户)

FOREIGN KEY(自己的列名) REFERENCES 对方表名(对方主键列名)

分为:一对多;一对一;多对多.

实例:员工和部门表关系:

     1,外键的类型要和主键类型保持一致;

         2,外键列中的值必须是主键列值的子集;

         3,插入数据时先插入主键;

         4,删除时,先删除从表(外键表是从表)

1,一对多:

create table t_department(

         id int auto_increment primary key,

         ...

)ENGINE InnoDB default charset utf8;

 

create table t_employee(

         id int auto_increment primary key,

         ...

         dept_id int,

         FOREIGN KEY(dept_id) REFERENCES t_department(id)

)ENGINE InnoDB default charset utf8;

 

2,多对多:需要建立中间关系表:

         create table student(

         id int PRIMARY key auto_increment,

         name varchar(20),

         age TINYINT

)ENGINE=INNODB DEFAULT CHARSET=utf8 auto_increment=10000;

 

create table course(

         id int PRIMARY key auto_increment,

         title varchar(20) unique,

         expire TINYINT

)ENGINE=INNODB DEFAULT CHARSET=utf8 auto_increment=10000;

 

create table relation(

         student_id int,

         course_id int,

         FOREIGN KEY(student_id) REFERENCES t_student(id),

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值