Mysql - delete from multiple tables with one query(Mysql - 用一个查询从多个表中删除)
问题描述
我有 4 个表,每个表存储有关用户的不同信息.每个表都有一个带有 user_id 的字段,用于标识哪一行属于哪个用户.如果我想删除用户,这是从多个表中删除该用户信息的最佳方法吗?我的目标是在一个查询中完成.
I have 4 tables that stores different information about a user in each. Each table has a field with user_id to identify which row belongs to which user. If I want to delete the user is this the best way to delete that users information from multiple tables? My objective is to do it in one query.
查询:
"DELETE FROM table1 WHERE user_id='$user_id';
DELETE FROM table2 WHERE user_id='$user_id';
DELETE FROM table3 WHERE user_id='$user_id';
DELETE FROM table4 WHERE user_id='$user_id';";
推荐答案
您可以使用 ON DELETE CASCADE
选项在表上定义外键约束.
You can define foreign key constraints on the tables with ON DELETE CASCADE
option.
然后从父表中删除记录会从子表中删除记录.
Then deleting the record from parent table removes the records from child tables.
检查此链接:http://dev.mysql.com/doc/refman/5.5/en/innodb-foreign-key-constraints.html
这篇关于Mysql - 用一个查询从多个表中删除的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Mysql - 用一个查询从多个表中删除


- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01