The difference between on and where conditions in left join association

The following content is reproduced

       When the database returns records by connecting two or more tables, it will generate an intermediate temporary table, and then return this temporary table to the user.

      When using left jion, the difference between on and where conditions is as follows:

1. The on condition is a condition used when generating a temporary table. It will return the records in the left table regardless of whether the condition in on is true.

2. The where condition is a condition for filtering the temporary table after the temporary table is generated. At this time, there is no meaning of left join (the records of the left table must be returned). If the condition is not true, all will be filtered out.

       Suppose there are two tables:

Table 1: Table 2:

id size   
10 AA
20 BB
30 CC
id size
10 AA
20 BB
30

CC

 

 

 

 

 

两条SQL:
1、select * form tab1 left join tab2 on (tab1.size = tab2.size) where tab2.name=’AAA’
2、select * form tab1 left join tab2 on (tab1.size = tab2.size and tab2.name=’AAA’)

The first SQL process:

1. Intermediate table
on condition: 
tab1.size = tab2.size    

tab1.id    tab1.size   tab2.size   tab2.name
1 10 10 AAA
2 20 20 BBB
2 20 20 BBB
3 30 null null

 

 

 

 

 

 

2. Then filter
the where condition on the intermediate table:
tab2.name='AAA'

tab1.id    tab1.size   tab2.size   tab2.name
1 10 10 AAA

 

 

 

The second SQL process:

1. Intermediate table
on condition: 
tab1.size = tab2.size and tab2.name='AAA'
(if the condition is not true, the records in the left table will also be returned)    

tab1.id    tab1.size   tab2.size   tab2.name
1 10 10 AAA
2 20 null null
3 30 null null


     

 

 

 

 

In fact, the key reason for the above results is the particularity of left join, right join and full join. Regardless of whether the condition on on is true or not, records in the left or right table will be returned. Full has the union of the characteristics of left and right. However, inner jion does not have this particularity, so the conditions are placed in on and where, and the result set returned is the same.

Original link: https://blog.csdn.net/wqc19920906/article/details/79785424

 

Guess you like

Origin blog.csdn.net/ZK_0705/article/details/106100254