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)
);
-- 实验表结构
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
更多关于MySQL相关内容感兴趣的读者可查看本站专题:《MySQL查询技巧大全》、《MySQL常用函数大汇总》、《MySQL日志操作技巧大全》、《MySQL事务操作技巧汇总》、《MySQL存储过程技巧大全》及《MySQL数据库锁相关技巧汇总》