我正在从多个表中删除某些行,如下所示:
我想在删除主表中的条目后清理某些表。我知道该条目的 ID(这是所有其他表中的 fid),但并非每个表都包含相关数据。
这是我想到的:
DELETE a, b, c
FROM tableA AS a
LEFT JOIN tableB AS b
ON a.fid = b.fid
LEFT JOIN tableC AS c
ON a.fid = c.fid
WHERE a.fid = 123
仅当 tableA 至少包含 fID
为 123
的行时,此方法才有效
当 tableA
没有匹配的行时,如何从 tableB
和 tableC
中删除某些行?
最佳答案
我认为最简单的方法是三个删除语句:
delete tableA where fid = 123;
delete tableB where fid = 123;
delete tableC where fid = 123;
如果您想将其作为一条语句来执行,请使用左外连接
,但从要删除的 ID 列表开始:
delete a, b, c
from (select 123 as fid
) todelete left outer join
tableA a
on todelete.fid = a.fid left outer join
tableB b
on todelete.fid = b.fid left outer join
tableC c
on todelete.fid = c.fid;
关于mysql - 删除至少一个为空的多个表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23953314/