好吧,首先让我介绍一下我的架构。
表:用户
Field | Type | Key | NN | AI
---------------------------------------------
id | int(11) | PRIM | YES | YES
username | varchar(50) | | YES | NO
banned | int(1) | | YES | NO
Foreign keys: none
表:Mac
Field | Type | Key | NN | AI
---------------------------------------------
id | int(11) | PRIM | YES | YES
address | varchar(50) | | YES | NO
lastacc | timestamp | | YES | NO
Foreign keys: none
表:usermac
Field | Type | Key | NN | AI
---------------------------------------------
userId | int(11) | PRIM | YES | NO
macId | int(11) | | YES | NO
Foreign keys:
[FK: macId] references macId to id in table macs
[FK: userId] references userId to id in table users
场景是,我有一个 userId,并希望删除 mac 中链接到该 userId 的所有记录(如 usermac 中的记录所述)
用户和mac的关系:一个用户可以拥有多个mac,一个mac可以属于多个用户。
我应该为此执行什么 SQL 查询?我尝试了级联删除,但级联不起作用。
预先感谢您的回答。
最佳答案
DELETE FROM mac WHERE id in (SELECT macId from usermac WHERE userId = <userId of deleted User>);
希望这有帮助。
关于MySQL如何在没有外键的情况下级联删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25098816/