如果连接表中的任何关联行对于特定列具有NULL,如何排除结果?

时间:2016-04-10 13:25:58

标签: sql postgresql

我想选择所有coach is trueavailable is true的唯一用户,但如果该用户有任何会话call_ends_at is null我不想包含该用户

call_ends_at可以为NULL或具有任意数量的各种日期。

用户

ID:整数
名称:字符串
coach:boolean
可用:布尔值

会话

ID:整数
coach_id:整数
call_ends_at:datetime

这是我尝试的内容:

SELECT DISTINCT "users".* FROM "users" 
INNER JOIN "sessions" ON "sessions"."coach_id" = "users"."id" 
WHERE "users"."coach" = true 
    AND "users"."available" = true 
    AND ("sessions"."call_ends_at" IS NOT NULL)

但如果存在包含非空call_ends_at列的会话,则仍会包含用户。

2 个答案:

答案 0 :(得分:1)

我认为您可以使用EXISTSNOT EXISTS执行您想要的操作:

SELECT u.*
FROM "users" u
WHERE u."coach" = true AND u."available" = true AND
      EXISTS (SELECT 1
              FROM "sessions" s
              WHERE s."coach_id" = u."id" 
             )
      NOT EXISTS (SELECT 1
                  FROM "sessions" s
                  WHERE s."coach_id" = u."id" AND
                        s."call_ends_at" IS NULL
                 );

答案 1 :(得分:1)

只需一个EXISTS即可实现:

SELECT u.*
FROM "users" u
WHERE u."coach" = true AND u."available" = true 
AND EXISTS
 (
   SELECT s."coach_id"
   FROM "sessions" s
   WHERE s."coach_id" = u."id"
   HAVING COUNT(*) = COUNT("call_ends_at") -- no NULLs
 )

取决于您的实际数据和指数戈登的答案可能更有效率。