sql (execution order of join on and where)

left join : Left join, returns all records in the left table and records with equal join fields in the right table.

right join : Right join, returns all records in the right table and records with equal join fields in the left table.

inner join: Inner join, also known as equijoin, returns only the rows with equal join fields in the two tables.

full join: outer join, returning rows from two tables: left join + right join.

Cross join: The result is a Cartesian product, which is the number of rows in the first table multiplied by the number of rows in the second table.

keyword: on

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: tab2

id size
1 10
2 20
3 30

Table 2: tab2

size name
10 AAA
20 BBB
20 CCC

两条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 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. 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, 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.

Guess you like

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