SQL - Left join, Right join, Inner join

Concept (Definition)

First, let’s introduce the definitions of these three

​Leftjoin: The left join is based on the left table, and connects the two tables according to the conditions of the two tables given after ON. As a result, all the query information in the left table will be listed, while the right table will only list the parts that satisfy the condition after ON and the left table. Left join is called left outer join, which is a type of outer join.

​Rightjoin: Right join, based on the right table, joins the two tables according to the conditions of the two tables given after ON. As a result, all the query information in the right table will be listed, while the left table will only list the parts that satisfy the condition after ON and the right table. Right join is called right outer join, which is a kind of outer join.

​Innerjoin: that is, an inner join, using the two tables as reference objects at the same time, and connecting the two tables according to the conditions of the two tables given after ON. As a result, only the parts of the two tables that satisfy the ON condition will be listed.

There is no full outer join in MySQL, so it is not explained here.


for example

​Just looking at the concept must be confusing, so give an example to make this concept more in-depth.

​Suppose, I have two tables A and B:

Form A

Form B

========= I ====================================================================================================================================== _ _ =

Leftjoin

​SQL语句:SELECT * FROM A LEFT JOIN B ONA.id=B.id

Result​:

Rightjoin

SQL语句:SELECT * FROM A RIGHT JOIN B ONA.id=B.id​

result:

Innerjoin

SQL语句:SELECT * FROM A INNER JOIN B ON A.id=B.id

result:

collective thinking understanding

According to the chestnuts above, it looks much clearer and more contrasting. If you still think that you only understand it now, but still find it a little difficult to use, you can use the following collective thinking, which I have only recently discovered, so it will be much simpler to think about it.

​We have two tables: A and B, then treat them as a set respectively

​Then our left and right outer joins and inner joins are equivalent to this ↓  ↓ 

A Left joinB -> A (According to the return requirements, the part of B with A and other conditions needs to be connected)

A Right join B-> B (according to the return requirements, the parts of A and B need to be connected)

A Inner join B->A∩B ​ ( The part that needs to be connected with conditions such as A and B according to the return requirement)

The illustration is like this ↓  ↓ 


Guess you like

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