删除除给定查询的结果之外的所有行

时间:2013-10-02 12:04:48

标签: mysql sql sql-delete

我有两个模型A和B以及一个关系表ab。

此查询显示关系表中的所有有效条目

select *
from ab
join a on (ab.a=a.id)
join b on (ab.b=b.id)
where a.pid=b.pid

如何删除所有无效条目,除了上述查询中的所有条目外?

2 个答案:

答案 0 :(得分:4)

delete from a
where id not in
(
    select * from 
    (
      select a.id
      from ab
      join a on (ab.a=a.id)
      join b on (ab.b=b.id)
      where a.pid=b.pid
    ) x
);

delete from b
where id not in
(
    select * from 
    (
      select b.id
      from ab
      join a on (ab.a=a.id)  
      join b on (ab.b=b.id)
      where a.pid=b.pid
    ) x
);

delete ab from ab
left join a on ab.a = a.id
left join b on ab.b = b.id
where a.pid <> b.pid
or a.id is null 
or b.id is null;

SQLFiddle demo

答案 1 :(得分:0)

假设您要删除无效关系,可能在DELETE中使用一对LEFT JOIN: -

DELETE ab
FROM ab
LEFT OUTER JOIN a ON ab.a = a.id
LEFT OUTER JOIN b ON ab.b = b.id
WHERE a.id IS NULL
OR b.id IS NULL

如果您还需要清理其他2个表,那么以下2个查询应该这样做: -

DELETE a
FROM a
LEFT OUTER JOIN ab ON a.id = ab.a
WHERE ab.a IS NULL


DELETE b
FROM b
LEFT OUTER JOIN ab ON b.id = ab.b
WHERE ab.b IS NULL