1

我有两个模型 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

如何删除所有无效条目,除了通过上述查询找到的条目之外的所有条目?

4

2 回答 2

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 演示

于 2013-10-02T12:06:46.813 回答
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
于 2013-10-02T12:09:59.280 回答