表与表的关联关系

一、一对多 :外键创在多的一方 ,先创一的一方,多的一方的外键要依赖一的一方的主键 。

    多对一  : 本质也一样 反过来即可 。

create table dept(
id int PRIMARY KEY AUTO_INCREMENT COMMENT '部门id',
dept_name VARCHAR(30) NOT NULL COMMENT '部门名称'
)

CREATE TABLE emp(
eid int PRIMARY key auto_increment COMMENT '员工id',
emp_name VARCHAR(30) NOT NULL  COMMENT '员工姓名' ,
did int ,
FOREIGN KEY(did) REFERENCES dept (id) 
)

二、一对一:

 2.1第一种方式:  就是在一对多的基础上 在多的一方的外键后加上唯一约束 unique 

create table wife (
wid int PRIMARY key  auto_increment ,
wname VARCHAR(30) NOT NULL 
)

create table husband (
hid int PRIMARY key  auto_increment ,
hname VARCHAR(30) NOT NULL ,
wid int UNIQUE,
FOREIGN key(wid)  REFERENCES wife(wid)
)

2.2第二种方式: 让一张表的主键同时作为另一张表的主键  同时这一张表的主键 不能自增 ,

因为是外键  可以重复 ,但是又是主键 便又不能重复 这样也就成为一对一。

create table person (
pid int PRIMARY key auto_increment,
pname VARCHAR(30) NOT NULL 
)

CREATE TABLE card (
cid int PRIMARY key ,
num VARCHAR(18),
FOREIGN key(cid) REFERENCES person(pid)
)

三 、多对多表的创建 :   作为联合主键 使这一对 不会出现重复的一对,

create table teacher (
tid int PRIMARY key auto_increment,
tname VARCHAR(30) NOT NULL 
)

create table teacher_student(
tid int ,
sid int ,
PRIMARY key (tid,sid) COMMENT'联合主键' , 
FOREIGN key (tid) REFERENCES teacher(tid),
FOREIGN key (sid) REFERENCES student(sid)
)

create table student (
sid int PRIMARY key auto_increment,
sname VARCHAR(30) NOT NULL 
)

猜你喜欢

转载自www.cnblogs.com/ych961107/p/12000928.html