【问题标题】:“Not exists” across multiple joins跨多个连接“不存在”
【发布时间】:2022-01-13 12:00:32
【问题描述】:

我正在学习 sql (postgres),id 喜欢查找不存在的值。

我有一个表,表 1 有 id,我想找到那些不在表 4 中的 id。

我必须在 3 个表之间加入,因为表 1 包含 id 和表 4 的 contact_id(不是同一个数字)

表 2,3 需要连接,因为它连接了 id。

那么我该如何处理“不存在”呢?

Select t1.id, table4.contact_id
From table1 t1
Join table2 using(id)
Join table3 using(id)
Join table4 using(contact_id)
Where not exists (
  Select 1
  From table4
  Where table4.contact_id=t1.id
  );

它不返回任何值,但应该 没有错误消息...

我认为我有思维错误

【问题讨论】:

    标签: postgresql join not-exists


    【解决方案1】:

    您的查询可能没有返回任何值,因为您在 contact_id 上加入了 table4,然后在 WHERE 子句中排除了来自此连接的行。

    要查找不存在的值,通常可以使用LEFT JOINRIGHT JOINFULL OUTER JOIN,然后在WHERE 子句中过滤具有NULL 值的行。

    试试这个:

    SELECT t1.id
    FROM table1 t1
    LEFT JOIN table2 t2 using(id)
    LEFT JOIN table3 t3 using(id)
    LEFT JOIN table4 t4 using(contact_id)
    WHERE t4.contact_id IS NULL
    

    【讨论】:

    • 就这么简单!谢谢
    猜你喜欢
    • 1970-01-01
    • 2014-12-29
    • 2010-10-21
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-30
    • 2016-02-17
    相关资源
    最近更新 更多