使用Join从多个表中删除行

时间:2011-11-14 16:30:53

标签: mysql join sql-delete multiple-tables

我正在尝试从连接的多个表中删除行。但是当我运行存储过程时,0行会受到影响。正如您所看到的,该函数非常广泛,但其想法是它将删除已连接的许多表中的行。

我该如何做到这一点?

CREATE DEFINER=`root`@`localhost` PROCEDURE `remove_tables_select1`(
    IN in_TableA_ID INT
    )
BEGIN   
    DELETE FROM TableB, TableC, TableD, TableE, TableA, TableF, TableG, TableH, TableI
    using TableB 
    inner join TableC on (TableC.ID = TableB.TableC_ID)
    inner join TableH on (TableH.TableB_ID = TableB.ID)
    inner join TableD on (TableD.TableB_ID = TableB.ID) 
    inner join TableE on (TableE.TableB_ID = TableB.ID) 
    inner join TableA on (TableA.ID = in_TableA_ID)
    inner join TableF on (TableF.TableA_ID = TableA.ID)
    inner join TableG on (TableG.TableA_ID = TableA.ID)
    inner join TableI on (TableI.TableH_ID = TableH.ID);
END

一个较小的例子:

CREATE DEFINER=`root`@`localhost` PROCEDURE `remove_tables_select1`(
    IN in_TableA_ID INT
    )
BEGIN   
    DELETE FROM TableA, TableB, TableC, TableD
    using TableA 
    inner join TableB on (TableB.ID = TableA.TableB_ID)
    inner join TableC on (TableC.TableB_ID = TableC.ID)
    inner join TableD on (TableC.TableD_ID = TableD.ID)
    WHERE TableA.ID = in_TableA_ID;
END

2 个答案:

答案 0 :(得分:0)

对于较小的示例,请尝试使用下一个查询 -

DELETE a, b, c, d FROM TableA a
JOIN TableB b
  ON b.ID = a.TableB_ID
JOIN TableC c
  ON c.TableB_ID = c.ID
JOIN TableD d
  ON c.TableD_ID = d.ID
WHERE
  a.ID = in_TableA_ID;

注意,使用INNER JOIN;检查相应的SELECT查询是否返回记录。

答案 1 :(得分:0)

这可能会带来一些开销,但请考虑使用FOREING KEYS删除CASCADE