首发日期:2018-04-12

|
1
2
3
4
5
6
7
|
create table student(id int primary key auto_increment,name varchar(15) not null,gender varchar(10) not null,cid int,foreign key(cid) references class(id)); |
|
1
2
3
4
|
create table class(id int primary key auto_increment,cname varchar(15)); |


|
1
|
foreign key(外键字段) references 父表 (主键) on delete set null on update cascade; |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
-- 实验表结构create table class(id int primary key auto_increment,cname varchar(15));create table student2(id int primary key auto_increment,name varchar(15) not null,gender varchar(10) not null,cid int,foreign key(cid) references class(id) on delete set null on update cascade);-- 实验表数据:insert into class(cname) values("python"),("linux"),("java"),("html5");insert into student2(name,gender,cid) values("Alice","female",1);insert into student2(name,gender,cid) values("John","female",2);insert into student2(name,gender,cid) values("Jack","female",3);insert into student2(name,gender,cid) values("Amy","female",4);select * from student2;select * from class;-- 尝试更新级联update class set id = 6 where cname="python";select * from student2; -- 结果原来的python的cid=6-- 尝试删除置空delete from class where cname="java";select * from student2; -- 结果原来的java的cid=null |