The difference between LEFT JOIN condition after ON and WHERE

with temp1 as (
    select model_no, model_name
    from d_extra.dim_mobile_model
    where model_no in ('vivox7', 'vivox9')
), temp2 as (
    select model_no, model_name
    from d_extra.dim_mobile_model
    where model_no in ('vivox7', 'sm-c7000')
)


select * 
from temp1 
left join temp2 
on temp1.model_no = temp2.model_no 
where temp2.model_no = 'vivox7'


result:
  temp1.model_no temp1.model_name temp2.model_no temp2.model_name
1 vivox7 vivo X7 vivox7 vivo X7




select * 
from temp1 
left join temp2 
on temp1.model_no = temp2.model_no 
and temp2.model_no = 'vivox7' 


result:
  temp1.model_no temp1.model_name temp2.model_no temp2.model_name
1 vivox7 vivo X7 vivox7 vivo X7
2 vivox9 vivo X9 NULL NULL


Recap:
use LEFT When JOIN, the
condition is placed directly behind ON, which is to filter first and then connect.

The condition is placed after the WHERE, which is to connect first and then filter


with temp1 as (
    select model_no, model_name
    from d_extra.dim_mobile_model
    where model_no in ('vivox7', 'vivox9')
), temp2 as (
    select model_no, model_name
    from d_extra.dim_mobile_model
    where model_no in ('vivox7','vivox9', 'sm-c7000')
)


select * 
from temp1 
inner join temp2 
on temp1.model_no = temp2.model_no 

where temp1.model_no = 'vivox7'


result:

  temp1.model_no temp1.model_name temp2.model_no temp2.model_name
1 vivox7 alive X7 vivox7 alive X7


select * 
from temp1 
inner join temp2 
on temp1.model_no = temp2.model_no 

and temp1.model_no = 'vivox7'


result:

  temp1.model_no temp1.model_name temp2.model_no temp2.model_name
1 vivox7 alive X7 vivox7 alive X7
No difference for inner join



select * 
from temp1 
left join temp2 
on temp1.model_no = temp2.model_no 

and temp1.model_no = 'vivox7'


result:

  temp1.model_no temp1.model_name temp2.model_no temp2.model_name
1 vivox7 alive X7 vivox7 alive X7
2 vivox9 alive X9 NULL NULL

  • Conclusion 
    When the filter condition is written on the left join on, all the data of the base table can be displayed, and the right table that does not meet the condition will be filled with null. When the filter condition is written on where, only the data that meets the filter condition will be displayed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325910049&siteId=291194637