【问题标题】:how to delete records from several child tables in the same query如何从同一查询中的多个子表中删除记录
【发布时间】:2011-05-26 09:15:00
【问题描述】:

我有一个这样的数据库模型, 一个母表我们称之为table_mother,还有几个子表。 table_mother 和 childs 之间的关系是这样的:

所有子表都有一个外键类型的名称作为母表的 id (id_table_mother)(关系是 1->n,因为 id_table_mother 是 uniq 并且 tbale child 可以获得 id_table_mother 的多个条目)

我想删除子表中与母表不再相关的所有记录,现在我尝试这样的方法

           DELETE FROM tb_child_1,tb_child_2,tb_child_3
              WHERE 
tb_child_1.id_table_mother 
AND tb_child_2.id_table_mother 
AND tb_child_3.id_table_mother
              NOT IN (SELECT id_table_mother FROM tb_table_mother);

谢谢

编辑:这就是我现在结束的方式

delete from tb_child_1 where id_mother not in (select id_mother from tb_mother_table);
delete from tb_child_2 where id_mother not in (select id_mother from tb_mother_table);

任何“全球”解决方案? 我的数据库也不是 innodb,所以我不能使用外键和其他东西

【问题讨论】:

  • 您可以在此处使用级联触发器,这是一个有用的链接 http://publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/com.ibm.sqls。 doc/sqls362.htm 看看有没有帮助
  • sry 无法访问该页面(未找到)
  • publib.boulder.ibm.com/infocenter/idshelp/v10/index.jsp?topic=/…‌​m.sqls.doc/sqls362.htm 复制并粘贴到浏览器地址栏中

标签: mysql sql-delete cascading-deletes


【解决方案1】:

您必须构建外键约束以在删除或更新时执行以了解有关外键约束的更多信息,请访问http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html

【讨论】:

  • 是的,但我的数据库不符合 innodb 标准(我没有做到,这是我检索到的东西),外键已设置但不是 innodb 图表...
【解决方案2】:

写 3 个这样的查询 -

DELETE
  tb_child_1
FROM
  tb_table_mother
LEFT JOIN
  tb_child_1
   ON tb_table_mother.id_table_mother = tb_child_1.id_table_mother
WHERE
   tb_child_1.id_table_mother IS NULL;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-20
    • 1970-01-01
    • 2013-01-30
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    相关资源
    最近更新 更多