如何借助复合主键关联查询结果删除Table_1中的对应记录?
复合主键批量删除的实现方案
针对复合主键(col_1、col_2)的批量删除需求,以下是几种实用的写法:
方法一:IN结合行构造器(主流数据库通用)
直接将表的复合主键列组合成行表达式,与子查询返回的主键集合匹配:
delete from thisTable where (col_1, col_2) IN ( select col_1, col_2 from thisTable where col_3 = 'criteria' )
该写法支持PostgreSQL、MySQL 8.0+、Oracle等多数主流数据库。
方法二:EXISTS子句(兼容性最强)
通过关联当前表与子查询的主键字段,精准定位待删除记录:
delete from thisTable t1 where exists ( select 1 from thisTable t2 where t2.col_3 = 'criteria' and t1.col_1 = t2.col_1 and t1.col_2 = t2.col_2 )
几乎所有关系型数据库都支持这种写法,兼容性拉满。
方法三:JOIN方式(MySQL/SQL Server专属)
部分数据库支持通过JOIN直接关联待删除记录:
MySQL版本
delete t1 from thisTable t1 join ( select col_1, col_2 from thisTable where col_3 = 'criteria' ) t2 on t1.col_1 = t2.col_1 and t1.col_2 = t2.col_2
SQL Server版本
delete t1 from thisTable t1 inner join ( select col_1, col_2 from thisTable where col_3 = 'criteria' ) t2 on t1.col_1 = t2.col_1 and t1.col_2 = t2.col_2
内容的提问来源于stack exchange,提问作者Edwin Mercado
相关产品推荐
相关产品推荐

