MySQL如何在没有外键的情况下级联删除

时间:2014-08-02 19:53:18

标签: mysql mysql-workbench

好的,首先让我介绍一下我的架构。

表:用户

Field    |     Type    |  Key  |  NN   | AI
---------------------------------------------
id       | int(11)     | PRIM  |  YES  | YES
username | varchar(50) |       |  YES   | NO
banned   | int(1)      |       |  YES   | NO

Foreign keys: none

table:macs

Field    |     Type    |  Key  |  NN   | AI
---------------------------------------------
id       | int(11)     | PRIM  |  YES  | YES
address  | varchar(50) |       |  YES   | NO
lastacc  | timestamp   |       |  YES   | NO

Foreign keys: none

table: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并希望删除链接到该userId的mac中的所有记录(如usermac中的记录所述)

用户与mac之间的关系:用户可以有多个mac,mac可以属于多个用户。

我应该为此执行哪些SQL查询?我尝试了级联删除,但级联不起作用。

提前感谢您的回答。

2 个答案:

答案 0 :(得分:1)

DELETE FROM mac WHERE id in (SELECT macId from usermac WHERE userId = <userId of deleted User>); 

希望这有帮助。

答案 1 :(得分:0)

越简越好:

DELETE FROM usermac WHERE userId=1;

将删除用户1的所有mac

相关问题