left join (the difference between on and where conditional placement)! ! ! !

   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 the condition used when generating the temporary table. It will return the records in the left table regardless of whether the condition in on is true or not .

2. The where condition is to filter 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), and all the conditions are filtered out if the conditions are not true.

 

 

 

 

 

Suppose there are two tables:

Table 1 tab1:

id size

1 10

2 20

3 30

Table 2 tab2:

size name

10 AAA

20 BBB

20 CCC


Two SQLs:
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 process of the first SQL:

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 CCC

3 30 (null) (null)

2, and then filter the intermediate table
where condition:
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, it will return the records in the left or right table, and full has the union of the characteristics of left and right. And inner jion does not have this particularity, then the condition is placed in on and where, and the returned result set is the same.

 

 

REFS:https://blog.csdn.net/u010368749/article/details/59482870

Guess you like

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