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.
LOGIN_ID
=roles.LOGIN_ID
WHERE roles.LOGIN_ID
=25774Error Code: 1451 Cannot delete or update a parent row: a foreign key constraint fails (
foodapp
.roles
, CONSTRAINTroles_ibfk_1
FOREIGN KEY (LOGIN_ID
) REFERENCESlogins
(LOGIN_ID
))Execution Time : 0 sec Transfer Time : 0 sec Total Time : 0.038 sec
最佳答案
如果您没有 ON CASCADE DELETE
约束设置,则需要先从子表中删除该行。然后,触发一个单独的查询以将其从父表中删除。
DELETE FROM roles
WHERE roles.`LOGIN_ID`=25774;
然后从父表中删除:
DELETE FROM logins
WHERE logins.`LOGIN_ID`=25774;
来自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. 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.
如果外键定义中使用了ON CASCADE DELETE
,那么您只需从父表中删除即可。它将自动从子表中删除相应的行。
关于mysql - mysql单查询如何删除有外键约束的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53362719/