如何在同一个查询中删除多个子表中的记录
我有一个像这样的数据库模型, 一张母表(我们称之为 table_mother)和几张子表。 table_mother和childs之间的关系是这样的:
所有表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 所以我不能使用外键之类的东西
I ve got a database modelize like this,
One mother table let's call it table_mother, and severals child tables.
Relation beetween table_mother and childs is like this:
All tables childs have a foreign key kind of name as the id of the mother table (id_table_mother) (relationship is 1->n as id_table_mother is uniq and tbale child can get several entries for id_table_mother)
I would like to delete all records in childs table wich are related no more with the mother table, for now i try something like this
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);
Thx
edit : this is how I ended for now
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);
any "global" solution ?
also my database is not innodb so I can 't go with foreigh keys and stuff
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您必须构建要在删除或更新时执行的外键约束,以了解有关外键约束的更多信息,请访问 http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
You have to build FOREIGN KEY Constraints to be performed on delete or update to know more about FOREIGN KEY Constraints visit http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
写 3 个这样的查询 -
Write 3 queries like this one -