我想选择所有 coach 为 true
且 available 为 true
的唯一用户,但如果该用户有任何 session ,其中 call_ends_at 为 null
我不想包括那个用户。
call_ends_at
可以为 NULL 或具有任意数量的各种日期。
用户
id:整数
名称:字符串
教练: bool 值
可用: bool 值
session
id:整数
coach_id:整数
call_ends_at:日期时间
这是我尝试过的:
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
列的 session ,这仍将包括用户。
最佳答案
-- I want to select all of the unique Users where coach is true and available is true
SELECT *
FROM users u
WHERE u.coach = true AND u.available = true
-- but if there are ANY Sessions for that user where call_ends_at is null
-- I don't want to include that user.
AND NOT EXISTS (
SELECT *
FROM sessions s
WHERE s.coach_id = u.id
AND s.call_ends_at IS NULL
) ;
关于sql - 如果连接表中的任何关联行的特定列为 NULL,我该如何排除结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36530357/