Left-Outer Join in Postgres Not Returning Values for Null

前端 未结 4 797
清歌不尽
清歌不尽 2021-01-04 13:07

A download is comprised of download-times, download-time id, and buno ID. Faults are comprised of fault-codes, download-time id, status, and type. A download can have many

4条回答
  •  孤街浪徒
    2021-01-04 13:50

    I'm giving my answer because I have significant doubts about the other answers. You gotta be careful about filter requirements. Remember, the where clause runs after your joins. So if there are any filter requirements in the where clause that refer to the non-outer joined table, you have (in many circumstances) nullified your outer join. So taking your sql, It seems the simplest solution is to either use the proper join or move the table names appropriately, and then move the filter conditions out of the where clause and into the join clause.

    SELECT  f.faultcode, f.downloadtimeid, d.downloadtime, count(*) as faultcount 
    FROM    download_time d 
    RIGHT OUTER JOIN fs_fault f ON 
        f.downloadtimeid = d.id
        AND f.faultcode IN (1000,1100)
        AND f.statusid IN(2, 4)
        AND d.downloadtime BETWEEN '04/11/2011' AND '05/01/2012')
        AND d.bunoid = 166501
    GROUP BY d.bunoid, f.downloadtimeid, d.downloadtime, f.faultcode
    

    Another way which I believe should be equivalent is

    SELECT  f.faultcode, f.downloadtimeid, d.downloadtime, count(*) as faultcount 
    FROM    download_time d 
    RIGHT OUTER JOIN fs_fault f ON 
        f.downloadtimeid = d.id
        AND d.downloadtime BETWEEN '04/11/2011' AND '05/01/2012')
        AND d.bunoid = 166501
    WHERE
        f.faultcode IN (1000,1100)
        AND f.statusid IN(2, 4)
    GROUP BY d.bunoid, f.downloadtimeid, d.downloadtime, f.faultcode
    

    As it doesn't strictly matter where the filter requirements on fs_fault are. (and your SQL engine's going to change that all up anyway).

    Edit: Here's a SQLFiddle demonstrating filtering on the join clause vs. the where clause.

提交回复
热议问题