检查关系是否存在

yqyhoc1h  于 2021-06-21  发布在  Mysql
关注(0)|答案(3)|浏览(297)

我有一个场景,其中 users 表中有一个配置文件 profiles table。
我正在检查用户是否使用此查询填写了特定字段:

SELECT users.displayName 
FROM `users` 
INNER JOIN profiles 
ON users.username = profiles.user_username 
WHERE (skills IS NULL OR skills = '') OR (background IS NULL OR background = '');

然后我使用这个查询来检查用户是否有一个配置文件:

SELECT *
FROM users
WHERE users.username NOT IN (SELECT user_username FROM profiles)

这是因为两个表中的相关字段都位于用户的用户名中。
是否可以将这两个查询合并起来,使其显示为select all users who not have a profile,or have a incomplete profile?
这可能是难以置信的简单,但我只是没有连接点。

6rqinv9w

6rqinv9w1#

您可以对profile使用左连接和che。username为null

SELECT users.displayName 
FROM `users` 
LEFT  JOIN profiles ON users.username = profiles.user_username 
WHERE ( (skills IS NULL OR skills = '') OR (background IS NULL OR background = '') )
and profiles.user_username is null
6tdlim6h

6tdlim6h2#

使用 not exists :

select u.*
from users u
where not exists (select 1
                  from profiles p
                  where p.user_username = u.username and
                        p.skills <> '' and
                        p.background <> ''
                 );
bz4sfanl

bz4sfanl3#

SELECT * FROM (

SELECT users.displayName 
FROM `users` 
INNER JOIN profiles 
ON users.username = profiles.user_username 
WHERE (skills IS NULL OR skills = '') OR (background IS NULL OR background = '');

UNION

SELECT *
FROM users
WHERE users.username NOT IN (SELECT user_username FROM profiles)
) x INNER JOIN

相关问题