亲宝软件园·资讯

展开

mysql外键 mysql外键基本功能与用法详解

随风行云 人气:0

本文实例讲述了mysql外键基本功能与用法。分享给大家供大家参考,具体如下:

本文内容:

首发日期:2018-04-12


什么是外键:


外键的增加:

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 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数据库计有所帮助。

加载全部内容

相关教程
猜你喜欢
用户评论