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),