当前位置:   article > 正文

SQL-基础 约束(添加-删除外键)_删除外键约束的sql语句

删除外键约束的sql语句

一.概念

  1. 约束:作用于表中字段上的规则,用于限制存储在表中的数据
  2. 目的:保证数据库中数据的正确,有效性和完整性。
  3. 分类:非空约束(not null),唯一约束(unique),主键约束(primary key),默认约束(default),检查约束(check),外键约束(foreign key)。

二.运用

创建约束表:(也可以直接在创建新表目录,选择创建约束,不需要写代码)

  1. create table user(
  2. id int primary key auto_increment comment '主键',
  3. name varchar(10) not null unique comment '姓名',
  4. age int check ( age > 0 && age <= 100 ) comment '年龄',
  5. status char(1) default '1' comment '状态',
  6. gender char(1) comment '性别'
  7. ) comment '用户表';

约束条件:

插入数据:(插入的数据一定要在约束条件内,否则报错)

insert into user(name,age,status,gender) values ('是1',99,'1','男'),('是二',22,'1','女');

三.外键约束

概念:用来让两张表的数据之间建立连接,保证数据的一致性和完整性

语法:

  1. create table 表名(
  2. 字段名 数据类型,
  3. ....
  4. [constraint] [外键名称] foreign key(外键字段名) references 主表(主表列名)
  5. );

准备副表数据:

  1. create table dept(
  2. id int auto_increment comment 'ID' primary key ,
  3. name varchar(50) not null comment '部门名称'
  4. )comment '部门表';
  5. insert into dept (id, name) values (1, '研发部'), (2, '市场部'), (3, '财务部'), (4, '销售部'), (5, '技术部');

运行结果:

主表数据:

  1. create table emp2(
  2. id int auto_increment comment 'ID' primary key ,
  3. name varchar(50) not null comment '姓名',
  4. age int comment '年龄',
  5. job varchar(20) comment '职位',
  6. salary int comment '薪资',
  7. entrydate date comment '入职时间',
  8. managerid int comment '直属领导ID',
  9. dept_id int comment '部门ID'
  10. )comment '员工表';

结果:

插入员工数据:

  1. insert into emp2 (id, name, age, job,salary, entrydate, managerid, dept_id) VALUES
  2. (1, '谢谢', 26, '董事长',30000, '2004-02-08', null,5),
  3. (2, '孙悟空', 56, '项目经理',20000, '2007-07-08', 1,1),
  4. (3, '猪八戒', 43, '开发',15000, '2012-05-12', 2,1),
  5. (4, '沙和尚', 38, '开发',17000, '2014-03-08', 2,1),
  6. (5, '唐僧', 57, '总经理',25000, '2016-02-12', 3,1),
  7. (6, '飞天', 67, '财务',11000, '2018-02-08', 2,1);

添加外键(注意表名的不同)

  1. --添加外键
  2. alter table emp2 add constraint fk_emp_dept_id foreign key (dept_id) references dept(id);

删除外键

  1. --删除外键
  2. alter table emp2 drop foreign key fk_emp_dept_id ;

外键的删除和更新行为:

  1. no action---当父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有不允许删除/更新
  2. restrict---当父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有不允许删除/更新
  3. cascade----当父表中删除/更新对应记录时,首先检查该记录是否有对应外键,如果有,则也删除/更新外键在子表中的记录
  4. set nll----当父表中删除对应记录时,首先检查该记录是否有对应外键,如果有则设置子表中该外键值为null
  5. set default---父表有变更时,子表将外键列设置成一个默认的值

演示cascade行为(也可以在表中点击modify table,shan删除/添加外键操作)

  1. --外键的删除和更新
  2. alter table emp2 add constraint fk_emp_dept_id foreign key (dept_id) references dept(id) on update cascade on delete cascade ;

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/497412
推荐阅读
相关标签
  

闽ICP备14008679号