zl程序教程

您现在的位置是:首页 >  数据库

当前栏目

sql 语句系列(删库跑路系列)[八百章之第七章]

SQL 系列 语句 第七章 八百 删库
2023-09-14 09:01:09 时间

前言

最开心的章节,没有之一。

删除违反参照完整性的记录

EMP 是员工表,DEPT 是部门表 DEPTNO是部门编号

delete from EMP where not exists (
select null from  DEPT where EMP.DEPTNO=DEPT.DEPTNO 
)
delete from EMP where DEPTNO not in(
select DEPTNO from DEPT
)

删除重复数据

删除名字相同的员工:

delete from EMP where

EMPNO not in(select MIN(EMPNO) from EMP group by ENAME)

原理很简单,保留ENAME 相同的一项即可。

删除被其他表参照的记录

这里面的意思,不是说因为一个表是另外一张表的外键,而无法删除。
而是说,根据一张表来删除另外一张表。
dept_accidents 是一张部门发生事故的表

select * from dept_accidents

现在有一个需求,就是删除出现3次事故的部门的员工删除。

delete from EMP
where DEPTNO in(select deptno from dept_accidents group by deptno having count(*)>=3)