Home  >  Article  >  Database  >  What is MySQL LEFT JOIN and how do we write MySQL queries for it?

What is MySQL LEFT JOIN and how do we write MySQL queries for it?

WBOY
WBOYforward
2023-08-23 19:05:021234browse

什么是 MySQL LEFT JOIN 以及我们如何为其编写 MySQL 查询?

When using a left join to connect two tables, the concepts of left table and right table are introduced, and a join predicate is also required. It returns all rows in the left table, including rows that satisfy the join predicate and rows that do not.

For rows that do not match the join-predicate, NULL will appear in the column of the right table in the result set. To understand it, let’s take an example of two tables named tbl_1 and tbl_2, which have the following data -

mysql> Select * from tbl_1;
+----+--------+
| Id | Name   |
+----+--------+
| 1  | Gaurav |
| 2  | Rahul  |
| 3  | Raman  |
| 4  | Aarav  |
+----+--------+
4 rows in set (0.00 sec)

mysql> Select * from tbl_2;
+----+---------+
| Id | Name    |
+----+---------+
| A  | Aarav   |
| B  | Mohan   |
| C  | Jai     |
| D  | Harshit |
+----+---------+
4 rows in set (0.00 sec)

Now, the query for LEFT JOIN can be as follows -

mysql> SELECT tbl_1.id,tbl_2.id FROM tbl_1 LEFT JOIN tbl_2 ON tbl_1.name = tbl_2.name;
+----+------+
| id | id   |
+----+------+
| 1  | NULL |
| 2  | NULL |
| 3  | NULL |
| 4  | A    |
+----+------+
4 rows in set (0.02 sec)

The above is the detailed content of What is MySQL LEFT JOIN and how do we write MySQL queries for it?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete