【问题标题】:Postgresql: Where conditions for joined table causing from table results to also not come backPostgresql:连接表的条件导致表结果也不会返回
【发布时间】:2018-03-28 02:17:52
【问题描述】:

我正在尝试编写一个查询,该查询将返回一个表中的数据,其中肯定会有一条记录,以及我要加入的另一个表的持续时间总和。我遇到的问题是,当在连接表中找不到任何结果时,它也不会导致任何内容从主表中返回。

这是一个示例查询:

select
to_json(a.*) as account,
sum(EXTRACT(epoch from (cr.end_time - cr.start_time) / 3600)) as hours_used,
from accounts a
left join conference_reservations cr on cr.account_id = a.account_id
where a.account_id = 'bdb25b1d-c337-4d7d-aecf-2c1aefd33656'
and cr.status IN ('confirmed', 'completed')
and cr.end_time BETWEEN '2018-04-15 05:00:00' and '2018-05-16 04:59:59'
group by a.*

所以基本上,如果没有记录符合 Conference_reservations 的条件,那么即使会找到帐户数据,我也不会得到任何回报。我宁愿 hours_used 为 null 或 0

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    将表 cr 上的条件移至该联接的 ON 子句。

    select
        to_json(a.*) as account,
        sum(EXTRACT(epoch from (cr.end_time - cr.start_time) / 3600)) as hours_used
    from accounts a
      left join conference_reservations cr 
         on cr.account_id = a.account_id
            and cr.status IN ('confirmed', 'completed')
            and cr.end_time BETWEEN '2018-04-15 05:00:00' and '2018-05-16 04:59:59'
    where a.account_id = 'bdb25b1d-c337-4d7d-aecf-2c1aefd33656'
    group by a.*
    

    现在,您将在 conference_reservations 表到达连接之前过滤它,而不是之后。这类似于执行子查询以从 conference_reservations 获取与您的 ON 子句中的过滤器匹配的记录,这将是另一种选择。

    【讨论】:

    • 非常感谢您的解决方案和解释!
    猜你喜欢
    • 1970-01-01
    • 2018-04-25
    • 1970-01-01
    • 2015-05-06
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多