PostgreSQL 在 where 子句存在时不返回行



我有两个表,一个是传感器记录发生的不同事件,另一个是包含所有可能事件列表的参考表。 传感器表当前为空。

SELECT
    events.eventtype,
    count(sensor.eventtype)
FROM
    events
    LEFT JOIN sensor ON sensor.eventtype = events.eventtype
GROUP BY
    events.eventtype

此查询正确返回事件及其发生的列表(所有内容为 0(

SELECT
    events.eventtype,
    count(sensor.eventtype)
FROM
    events
    LEFT JOIN sensor ON sensor.eventtype = allevents.eventtype
WHERE
    eventdate = '2019-06-19'
GROUP BY
    events.eventtype

但是,此查询不返回任何内容。 where 子句有什么区别?

您需要将过滤条件移动到 on 子句:

SELECT e.eventtype, count(s.eventtype)
FROM events e LEFT JOIN
     sensor s
     ON s.eventtype = e.eventtype AND
        s.eventdate = '2019-06-19'
GROUP BY e.eventtype;

对于不匹配项,LEFT JOIN返回一个NULL值。 使用 WHERE 子句中的条件,这些将被过滤掉。

作为一般规则,当使用LEFT JOIN时,第一个表的条件在WHERE子句中。 后续表的条件包含在ON子句中。

最新更新