是否可以通过单个查询删除不同表中具有相同外键的记录?

时间:2013-08-16 05:04:10

标签: mysql sql

我需要使用单个sql查询删除具有相同外键ID的所有多个表中的记录。我给出了下面的例子,

Table Name : basetable
id | column1
---|---------
 1 |  BCol1
 2 |  BCol2

Table Name : Reftable1

id | BaseTableID | Column1
---|-------------|--------
 1 |      1      | RT1Col1
 2 |      1      | RT1Col2

Table Name : Reftable2

id | BaseTableID | Column1
---|-------------|--------
 1 |      2      | RT2Col1
 2 |      1      | RT2Col2

Table Name : Reftable3

id | BaseTableID | Column1
---|-------------|--------
 1 |      1      | RT3Col1
 2 |      2      | RT3Col2

在上面三个参考表中,我想删除具有单个mysql查询的BaseTableID = 1的记录。有没有可能请分享你的想法

3 个答案:

答案 0 :(得分:2)

我认为这样做会:

DELETE r1, r2, r3
FROM Reftable1 r1
JOIN Reftable2 r2
JOIN Reftable3 r3
WHERE r1.BaseTableID = 1
AND r2.BaseTableID = 1
AND r3.BaseTableID = 1

SQLFIDDLE

如果某些表可能没有匹配的行,则此LEFT JOIN应该执行此操作:

DELETE r1, r2, r3
FROM basetable b
LEFT JOIN Reftable1 r1 ON b.id = r1.BaseTableID
LEFT JOIN Reftable2 r2 ON b.id = r2.BaseTableID
LEFT JOIN Reftable3 r3 ON b.id = r3.BaseTableID
WHERE b.id = 1

SQLFIDDLE

答案 1 :(得分:1)

创建表时,您必须指定on cascade delete

baseTable id references BaseTable(id) on delete cascade

有关详细信息,请参阅http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

答案 2 :(得分:1)

您可以通过以下连接删除:

DELETE FROM basetable
INNER JOIN Reftable1
  ON basetable.id = Reftable1.BaseTableID
INNER JOIN Reftable2
  ON basetable.id = Reftable2.BaseTableID
INNER JOIN Reftable3
  ON basetable.id = Reftable3.BaseTableID
WHERE basetable.id = ?