当前位置:Gxlcms > 数据库问题 > sql example 3 -- foreign_key

sql example 3 -- foreign_key

时间:2021-07-01 10:21:17 帮助过:3人阅读

table if exists test1; create table test1 ( id int auto_increment primary key, name varchar(20) NOT NULL );
drop table if exists test2;
create table test2 (       # error 150, 错误 类型不同
id2 smallint primary key auto_increment,
name2 varchar(10) not null,
foreign key (id2) references test1 (id)
);
drop table if exists test2;
create table test2 (
id2 int auto_increment primary key,
name2 varchar(10) not null,
foreign key (id2) references test1 (id)
);

父表: test1
子表: test2

foreign key 默认: 父表和子表的行为

on delete -—

cascade 从父表删除或者更新且 自动删除或者更新子表 中匹配的行
set null 从父表删除或者更新行, 并设置子表中的外键列为 NULL
restrict 拒绝对父表的删除或者更新操作
no action 标准 sql 关键字, 和 restrict (mysql 特有) 相同 (是默认值)
create table test3 (
id3 int primary key auto_increment,
name3 varchar(10) not null,
foreign key (id3) references test1 (id) on delete cascade
);
drop table test3, test2, test1;

sql example 3 -- foreign_key

标签:

人气教程排行