Postgresql:从表结果导致联接表的条件也不会返回

时间:2018-03-27 18:08:53

标签: sql postgresql

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

以下是一个示例查询:

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

1 个答案:

答案 0 :(得分:0)

将表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子句中的过滤器匹配的记录,这可能是另一种选择。