我需要从数据库表中删除一些特定的记录,但表本身没有主键.所以条件取决于其他表.那么这样做的正确方法是什么?
delete from table_1
where exists
(select distinct tb.*
from table_1 tb, table_2 tb_2, table_3 tb_3
where tb1.col = tb2.col
and tb3.col = tb2.col
and tb3.col_2= 10)
Run Code Online (Sandbox Code Playgroud)
这是正确的方法吗?让我们说table_1有4列,前两列应该是要删除的标准.
如果查询的选择版本返回您想要删除的结果,那么就可以了。不过有几件事..
使用符合 ANSI 的显式连接语法,而不是逗号分隔的隐式语法(这种语法早已被弃用)。无论如何,显式语法看起来更好并且更容易阅读。
将您的EXISTS背部与主表相关联。而且你不需要一个distinct,无论有1个匹配行还是100亿,它都会返回正值。
SELECT *
FROM table_1 tb_1
WHERE EXISTS (SELECT *
FROM table_2 tb_2
JOIN table_3 tb_3 ON tb_2.col = tb_3.col
WHERE tb_1.col = tb_2.col
AND tb_3.col_2 = 10)
Run Code Online (Sandbox Code Playgroud)