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 - 用一个查询从多个表中删除
基础教程推荐
- 在 SQL 中连接多个表 2021-01-01
- 需要 MySQL 5.1 中的抽象触发器来更新审计日志 2021-01-01
- SQL Server 实例在登录协商期间返回无效或不受支持的协议版本 2021-01-01
- SQL:使用来自具有相同列名的两个表中的数据... 2021-01-01
- 是否可以执行按位分组功能? 2021-01-01
- SQL 效率:WHERE IN 子查询 vs. JOIN 然后 GROUP 2021-01-01
- 无法解决整理冲突 2021-01-01
- 如何使用 mysql.connector 禁用查询缓存 2022-01-01
- SSMS 中的权限问题:“对象 'extended_properties'、数据库 'mssqlsystem_resource'、... 错误 229)上的 SELECT 权限被拒绝" 2022-01-01
- 将 SQL Server DateTime 列迁移到 DateTimeOffset 2021-01-01
