4 foreign key 表关联

#先建被关联的表,并保证被关联的字段唯一 再建被关联的表

#1 建立表关系:
create table dep(
    id int primary key,
    name char(16),
    comment char(50)
);


create table emp(
    id int primary key,
    name char(10),
    sex enum('male','female'),
    dep_id int,
    foreign key(dep_id) references dep(id) 
    on delete cascade 
    on update cascade
);


#2 插入数据: 先插入被关联表记录
insert into dep values
(1,'IT','技术能力有限部门'),
(2,'销售','销售能力有限部门'),
(3,'财务','花钱特别多部门');


#再往关联表插入记录
insert into emp values
(1,'eddie','male',1),
(2,'kevin','male',1),
(3,'赵晓迪','female',3),
(4,'iris','female',2);


delete from emp where dep_id=1; #删除的时候先删除被关联的表数据

delete from dep where id=1;


update dep set id=3333 where id =3;

 

你可能感兴趣的:(4 foreign key 表关联)