MySQL数据库中外键SQL语句的编写
1. 外键约束作⽤
外键约束:对外键字段的值进⾏更新和插⼊时会和引⽤表中字段的数据进⾏验证,数据如果不合法则更新和插⼊会失败,保证数据的有效性
2. 对于已经存在的字段添加外键约束
添加外键约束: alter table 从表 add foreign key(外键字段) references 主表(主键字段);
-- 为cls_id字段添加外键约束
alter table students add foreign key(cls_id) references classes(id);  【⾸先会验证的,不符合就会报错】
简单的mysql语句
alter table teacher add foreign key(id) references school(id);
3. 在创建数据表时设置外键约束
-- 创建学校表
create table school(
id int not null primary key auto_increment,
name varchar(10)
);
-- 创建⽼师表
create table teacher(
id int not null primary key auto_increment,
name varchar(10),
s_id int not null,
foreign key(s_id) references school(id)
);
4. 删除外键约束
删除外键约束: alter table 表名 drop foreign key 外键名;
-- 需要先获取外键约束名称,该名称系统会⾃动⽣成,可以通过查看表创建语句来获取名称show create table teacher;
-- 获取名称之后就可以根据名称来删除外键约束
alter table teacher drop foreign key 外键名;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。