mysql - 比较两个数据库表中的两个值
问题描述
我有许多数据库表,其中包含来自注册用户的数据。删除用户后,该特定用户的数据仅从一个数据库表中删除(table 1
例如)。
因此,我需要将current_user_id
所有其他相关表与user_id
from进行比较table 1
,如果该值不存在于table 1
具有该特定 id 的那些表中的所有其他值中,则需要删除。
例如,如果我有这两个数据库表:
table 1
id | user_id|
------------
1 | 14 |
2 | 15 |
3 | 16 |
4 | 17 |
table 2
id | current_user_id |
----------------------
21 | 14 |
22 | 15 |
23 | 16 |
24 | 17 |
25 | 18 |
user_id
并且current_user_id
是来自两个不同表的相同值。
如果缺少该值,我需要遍历user_id
,比较current_user_id
并删除每个。(已删除)current_user_id
user_id
例如:如果我有current_user_id=14
而我没有,user_id=14
那么我需要current_user_id=14
被删除。
解决方案
With NOT EXISTS
:
delete t2 from table2 t2
where not exists (
select 1 from table1 t1
where t1.user_id = t2.current_user_id
);
See the demo.
Or with a LEFT JOIN
of table2
to table1
which will delete the unmatched rows:
delete t2
from table2 t2 left join table1 t1
on t1.user_id = t2.current_user_id
where t1.user_id is null;
See the demo.
推荐阅读
- python - 对于 sqlalchemy,我可以将原始 sql 和 orm 模型结合在一起吗?
- google-admin-sdk - Google 工作区 ADMIN SDK 目录 API 返回 403
- powershell - 使用 PowerShell 创建 JSON 策略文档
- c# - 字体对象缺少属性(间距)
- oracle - 选择不活跃的客户
- swift - Swift Firebase:如何在列表中添加新问题?
- pytorch - 更改输入后如何重新计算梯度?火炬
- node.js - React Native 发送邮件
- ms-access-2016 - 访问表单事件 - 使用什么控件来动态执行代码
- c# - C# WPF 中的错误:“System.Windows.Style”不是属性“System.Windows.Controls.Control.Template”的有效值