0

我需要使用单个 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 的记录。有没有可能请分享你的想法

4

3 回答 3

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

于 2013-08-16T05:08:48.987 回答
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

于 2013-08-16T05:09:18.663 回答
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 = ?
于 2013-08-16T05:12:57.290 回答