我想选择所有coach is true
和available 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
列的会话,则仍会包含用户。
答案 0 :(得分:1)
我认为您可以使用EXISTS
和NOT 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
)
取决于您的实际数据和指数戈登的答案可能更有效率。