简体   繁体   中英

Left join, where clause

I'm wondering why this returns no values but if I place the "and r2.ref_nm = 'memberPrograStatusType" in the join clause it returns values. The 'memberPrograStatusType is null.

`select mp.mbr_id
,r1.ref_desc as program_name
,r2.ref_desc as program_status
,mp.nom_dt
,mp.enrl_dt
,mp.end_dt
from icue.mbr_pgm mp
  left join icue.ref r1 on mp.pgm_typ_id = r1.ref_cd
  left join icue.ref r2 on mp.mbr_pgm_sts_typ_id = r2.ref_cd  
where '15-JAN-17' between mp.enrl_dt and nvl(mp.end_dt,sysdate)
    and mp.mbr_id = 46714641
    and r1.ref_nm = 'programType'
    and r2.ref_nm = 'memberPrograStatusType'
'

The reason is because when you place a filter from a column in the left join in the where clause, you are turning it into an inner join.

However if you place the filter on the join clause then the filter applies only to the rows that have data in left join table.

The key here is order of operations

WHERE is applied after JOIN

If you put r2.ref_nm = 'x' into the JOIN predicate, it is applied against the right table, which is then joined to the left table. Because you are using a LEFT JOIN , this means that the rows joined from the right table are filtered on r2.ref_nm = 'x' , but all rows from the left table are still preserved in the result set.

If you put r2.ref_nm = 'x' into the WHERE clause, then it is applied to the entire result set , after the joins have occured. This essentially makes your LEFT JOIN into an INNER JOIN if your filter is looking for anything other than NULL

TLDR: if you want to filter on the right table in a LEFT JOIN , you have to do so in the join predicate, otherwise you will lose all the NULL values that are created from the LEFT JOIN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM