foreign key 和on delete/update cascade用法

创建 foreign key步骤

  • 确立表关系即主表和被关联表

  • 需要先建立被关联表(指定被关联字段唯一)

create table 表名
(
	字段名 类型 [限定条件],
	字段名 类型 [限定条件],
);


如:
create table deptment
(
	dep_id int  primary key,
	dep_name char(20),
	dep_comment varchar(6)
);


  • 建立主表限定关联表
create table 表名
(
	字段名 类型 [限定条件],
	字段名 类型 [限定条件],
	...
	关联字段名 类型,
	foreign key(关联字段名 ) references deptment(depid) on delete cascade on update cascade
	#指定主表外键字段和关联的被关联表和被关联字段
	#on delete/update cascade 作用是删除/更新对应关联信息后对应关联表自动删除/更新对应信息 ,不指定则删除/更新被关联表中数据主表不会删除/更新
);


如:
create table employee
(
	emp_id int  primary key,
	emp_name char(20),	
	emp_comment varchar(255),
	dep_id int,
	foreign key(dep_id) references deptment(dep_id) on delete cascade on update cascade
);


on delete/update cascade

  • 用法
请看上面的示例
  • 作用
on delete/update cascade 作用是删除/更新对应关联信息后对应关联表自动删除/更新对应信息 

示例

  • 创建表后查看如下:

在这里插入图片描述

  • 添加deptment数据
    insert into deptment(dep_id,dep_name,dep_comment) values(1,‘IT’,‘it’);
    insert into deptment(dep_id,dep_name,dep_comment) values(2,‘Sale’,‘sale’);
    部门查询

  • 添加employee 数据
    insert into employee values(1,‘fzl’,‘excellent’,1);
    insert into employee values(2,‘Bob’,‘good’,2);
    员工数据

  • 查看两张表的数据
    联合查询到的数据

  • 删除部门2 查看结果

删除数据查询结构
可以看到employee中 dep_id=2的记录自动删除了 哇 amazing

更新也一样 so easy

注:只能是更改/删除被关联表 主表中的记录自动删除/更新 反过来是不成立的


猜你喜欢

转载自blog.csdn.net/fzl_blog/article/details/106311614