首页 > 解决方案 > 比较两个数据库表中的两个值

问题描述

我有许多数据库表,其中包含来自注册用户的数据。删除用户后,该特定用户的数据仅从一个数据库表中删除(table 1例如)。

因此,我需要将current_user_id所有其他相关表与user_idfrom进行比较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_iduser_id

例如:如果我有current_user_id=14而我没有,user_id=14那么我需要current_user_id=14被删除。

标签: mysql

解决方案


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.


推荐阅读