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

标签 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

表: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/

相关文章:

php - MAX(user_id) 不起作用

javascript - MYSQL 和 Nodejs 异步问题中的嵌套查询

MySQL Workbench 创建前向脚本以错误的顺序删除表,违反外键约束

mysql - 如何用另一个表更新表记录

c# - 不使用数据源控件的 gridview Inner Join 查询

使用 mysqli innerjoin 的 PHP 函数

php - 读取查询的多个结果并将其显示到 php 生成的表中

mysql - 从所有数据库的查询结果中获取顶部记录

MySQL 1050 表不存在,但 MySQL 认为它存在

php - 使用格式显示来自查询的多个值