Difference between left join, right join, inner join, full join

refer to

https://www.cnblogs.com/assasion/p/7768931.html

https://blog.csdn.net/rongbo_j/article/details/46352337

There are four ways to connect query in sql: inner join, left join, right join, and full join. There is not much difference between them, just query The results that came out were different.
For example we have two tables:
write picture description here

The Orders table is associated with the Persons table through the foreign key Id_P.

1. Inner join, when the two tables are joined and queried, only the result sets that match exactly in the two tables are retained.

We use inner join to query the two tables, the sql is as follows:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
INNER JOIN Orders
ON Persons.Id_P=Orders.Id_P
ORDER BY Persons.LastName

Query result set:
write picture description here

In this connection method, if the Id_P field in the Orders table cannot find a match in the Persons table, it will not be listed.

2. Left join, when two tables are connected, all rows in the left table will be returned, even if there are no matching records in the right table.

We use left join to query the two tables, the sql is as follows:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
LEFT JOIN Orders
ON Persons.Id_P=Orders.Id_P
ORDER BY Persons.LastName

The query results are as follows:
write picture description here
You can see that the Id_P field of the row whose LastName is Bush in the left table (Persons table) does not match in the right table (Orders table), but the query result still retains this row.

3. Right join, when two tables are connected, all rows in the right table will be returned, even if there are no matching records in the left table.

We use right join to connect the two tables, the sql is as follows:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
RIGHT JOIN Orders
ON Persons.Id_P=Orders.Id_P
ORDER BY Persons.LastName

The query results are as follows:

write picture description here
The Id_P field value of the last record in the Orders table is 65, and there is no record in the left table that matches it, but it is still reserved.

4.full join, when the two tables are connected and queried, all unmatched rows in the left table and the right table are returned.

We use full join to query the two tables, the sql is as follows:

SELECT Persons.LastName, Persons.FirstName, Orders.OrderNo
FROM Persons
FULL JOIN Orders
ON Persons.Id_P=Orders.Id_P
ORDER BY Persons.LastName

The query result is as follows:
write picture description here
The query result is the union of left join and right join.

The difference between these join queries is just that.

 

Guess you like

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