数据库sql语句如何设置外键

2021-02-13

数据库sql语句设置外键的方法:1、添加外键约束【alter table 从表 add foreign key(外键字段) references 主表(主键字段)】;2、删除外键约束【alter table 表名 drop foreig】。

/2021/02/86f3e464.jpg

本文操作环境:Windows7系统,Microsoft SQL Server2008版本,Dell G3电脑。

推荐:sql视频教程

数据库sql语句设置外键的方法:

1、外键约束作用

外键约束:对外键字段的值进行更新和插入时会和引用表中字段的数据进行验证,数据如果不合法则更新和插入会失败,保证数据的有效性

2、对于已经存在的字段添加外键约束

-- 为cls_id字段添加外键约束
alter table students add foreign key(cls_id) references classes(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、删除外键约束

-- 需要先获取外键约束名称,该名称系统会自动生成,可以通过查看表创建语句来获取名称
show create table teacher;
-- 获取名称之后就可以根据名称来删除外键约束
alter table teacher drop foreign key 外键名;

以上就是数据库sql语句如何设置外键的详细内容,更多请关注北冥有鱼其它相关文章!

本文转载自【PHP中文网】,希望能给您带来帮助,苟日新、日日新、又日新,生命不息,学习不止。

《数据库sql语句如何设置外键.doc》

下载本文的Word格式文档,以方便收藏与打印。