sql - 如果连接表中的任何关联行的特定列为 NULL,我该如何排除结果?

标签 sql postgresql

我想选择所有 coach 为 trueavailable 为 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/

相关文章:

sql - Postgres 中的向量(数组)加法

ruby-on-rails - 如何让 datamapper 与 postgresql 数据库一起工作?

postgresql - 如何在 Postgresql 中创建具有初始大小的表空间?

postgresql - 如何在 Postgres 中实现包含运算符

sql - 当一个值与其他值不同时,SQL Server

php - 如何在更新前检查另一个表?

mysql - 像 JOIN 一样创建表

php - 使用 PHP PDO 逐行将 CSV 插入 Postgres

php - mysql连接表并接收一行

php - 检查多行 - PHP 和 MySQL