简体   繁体   English

如何在MySQL单个查询中删除具有外键约束的记录

[英]How to delete records with foreign key constraint in mysql single query

DELETE logins, roles 
FROM logins
INNER JOIN roles ON logins.`LOGIN_ID`=roles.`LOGIN_ID`
WHERE roles.`LOGIN_ID`=25774;

Query: DELETE logins, roles FROM logins INNER JOIN roles ON logins. 查询:DELETE登录名,FROM登录名的角色INNER JOIN登录名的角色。 LOGIN_ID =roles. LOGIN_ID =角色。 LOGIN_ID WHERE roles. LOGIN_ID WHERE个角色。 LOGIN_ID =25774 LOGIN_ID = 25774

Error Code: 1451 Cannot delete or update a parent row: a foreign key constraint fails ( foodapp . roles , CONSTRAINT roles_ibfk_1 FOREIGN KEY ( LOGIN_ID ) REFERENCES logins ( LOGIN_ID )) 错误代码:1451无法删除或更新父行,外键约束失败( foodapproles ,约束roles_ibfk_1外键( LOGIN_ID )参考文献loginsLOGIN_ID ))

Execution Time : 0 sec Transfer Time : 0 sec Total Time : 0.038 sec 执行时间:0秒传输时间:0秒总时间:0.038秒

If you don't have ON CASCADE DELETE constraint setup, you will need to Delete the row from child table first. 如果没有ON CASCADE DELETE约束设置,则需要首先从子表中删除行。 And, then fire a separate query to delete it from the parent table as well. 并且,然后触发一个单独的查询以将其也从父表中删除。

DELETE FROM roles 
WHERE roles.`LOGIN_ID`=25774;

And, then delete from parent table: 并且,然后从父表中删除:

DELETE FROM logins
WHERE logins.`LOGIN_ID`=25774;

From Documentation : 文档

If you use a multiple-table DELETE statement involving InnoDB tables for which there are foreign key constraints, the MySQL optimizer might process tables in an order that differs from that of their parent/child relationship. 如果您使用涉及具有外键约束的InnoDB表的多表DELETE语句,则MySQL优化器可能以与其父/子关系不同的顺序处理表。 In this case, the statement fails and rolls back. 在这种情况下,该语句将失败并回滚。 Instead, you should delete from a single table and rely on the ON DELETE capabilities that InnoDB provides to cause the other tables to be modified accordingly. 相反,您应该从单个表中删除,并依靠InnoDB提供的ON DELETE功能来相应地修改其他表。


If ON CASCADE DELETE has been used in the Foreign Key definition, then all you need to do is delete from the Parent table only. 如果ON CASCADE DELETE键定义中使用了ON CASCADE DELETE ,那么您只需要从父表中删除即可。 It will automatically delete the corresponding rows from the Child table(s). 它将自动从子表中删除相应的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM