仅使用一个约束进行多重删除

时间:2015-02-24 20:36:07

标签: mysql sql sql-delete

我有3张桌子,让他们说a,b,c,他们都有一个带有ID的列。当来自不同表的行彼此属于时,ID对应。我想使用id删除表中的所有条目。我尝试了以下多重删除:

delete from a,b,c from a,b,c where a.id=123;

以下不会起作用

delete from a,b,c from a,b,c where a.id=b.id and b.id=c.id and c.id=123;

因为当a中有一个元素而a中有一个元素并且只有一个元素存在于给定id时,并不强制要求c中的元素。

2 个答案:

答案 0 :(得分:2)

根据the documentation,语法为:

delete a,b,c 
from a
LEFT JOIN b ON a.id = b.id
LEFT JOIN c ON a.id = c.id 
where a.id=123;

答案 1 :(得分:1)

我会设置一个数组,并使用它来命名要从具有您要查找的ID的每个表名中删除的表。这样,如果id是外键id,您将拥有更多控制权。通过foreach循环运行。

$ table = array(tablea => a,id => a),array(tableb => b,id => b)

$ sql =" DELETE FROM $ table WHERE $ where&#34 ;;