Mysql
主页 > 数据库 > Mysql >

mysql外键基本功能与用法的介绍

2020-04-15 | 秩名 | 点击:

本文内容:

首发日期: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
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
 

补充:

原文链接:https://www.cnblogs.com/progor/p/8799922.html
相关文章
最新更新