Mysql 的每一行检查使用如果一个字段在另一个表中,如果没有删除该行

问题描述

我有两个表,第一个称为“用户”,第二个称为“配置文件”。两个表都有一个名为“id”的字段,profiles 表也有一个名为“user_id”的字段,我用它来连接两个表。长话短说,当用户删除时,他们的配置文件没有(该问题已解决),我想在配置文件表中找到所有没有用户连接到他们的配置文件。我需要以某种方式检查配置文件表中的每一行,以查看 'user_id' 字段是否存在于字段 'id' 下的 'users' 表中,以及它是否不删除配置文件表中包含该 'user_id' 的行.

解决方法

您可以使用not exists

select p.*
from profiles p
where not exists (select 1 from users u where p.profile_id = u.id);

如果要删除行:

delete p from profiles p
where not exists (select 1 from users u where p.profile_id = u.id);