我有表A和B.表B的项目也可能存在于表A中,我想删除这些项目。这样做的SQL语句会是什么样的?
答案 0 :(得分:6)
这是一个选项
delete from a
where a.key in (select key from b)
答案 1 :(得分:3)
或者:
DELETE a
WHERE a.some_field IN (SELECT some_field FROM b)
或
DELETE A
WHERE EXISTS (SELECT 1 FROM b WHERE b.field1 = a.field2)
根据您的数据库,您可能会发现其中一个比另一个更好。 IIRC Oracle倾向于选择WHERE EXISTS IN,但这可能取决于许多因素。
答案 2 :(得分:2)
类似的东西:
DELETE
FROM TableA as A
WHERE A.ID IN (SELECT ID
FROM TableB AS B
WHERE [your condition here])
答案 3 :(得分:2)
在某些数据库中,相当奇特的DELETE FROM FROM是非常高效
delete from foo from foo as f
where exists
(
select 1 from bar as b where b.field = f.field
)
答案 4 :(得分:1)
如果您的表使用InnoDB,最简单的方法是使用表B中的foreign keys设置表A,并使用ON DELETE CASCADE。这样就不需要更改代码,并且可以保证数据库的完整性。
答案 5 :(得分:1)
根据标准允许这样做。
delete a from a join b on a.id = b.id;
答案 6 :(得分:0)
delete a
--select a.*
from tablea a
join tableb b on a.someid = b.someid
确保首先运行选择部分,以确保获得所需的记录。
答案 7 :(得分:0)
DELETE FROM FIRST_TABLE FT
WHERE EXISTS(
SELECT 1
FROM SECOND_TABLE ST
WHERE ST.PRIMARY_KEY = FT.PRIMARY_KEY
);