本文主要是介绍mysql的inner join 和left join区别,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. INNER JOIN
INNER JOIN 只返回两个表中满足连接条件的匹配行。换句话说,它只返回那些在连接的两个表中都有匹配值的行。如果某一行在其中一个表中没有匹配项,那么这行不会出现在结果集中。
写法:
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;
假设有两个表 employees 和 departments:
employees:
+----+----------+------------+
| id | name | dept_id |
+----+----------+------------+
| 1 | Alice | 1 |
| 2 | Bob | 2 |
| 3 | Charlie | NULL |
+----+----------+------------+departments:
+----+--------------+
| id | department |
+----+--------------+
| 1 | HR |
| 2 | Engineering |
| 3 | Marketing |
+----+--------------+
执行 INNER JOIN:
SELECT employees.name, departments.department
FROM employees
INNER JOIN departments
ON employees.dept_id = departments.id;
结果为:
+--------+--------------+
| name | department |
+--------+--------------+
| Alice | HR |
| Bob | Engineering |
+--------+--------------+
2. LEFT JOIN
LEFT JOIN 返回左表中的所有行,即使在右表中没有匹配项。在这种情况下,右表中的结果为 NULL。
用法:
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;
同上文中提到的表,执行以下SQL
SELECT employees.name, departments.department
FROM employees
LEFT JOIN departments
ON employees.dept_id = departments.id;
执行结果如下:
+--------+--------------+
| name | department |
+--------+--------------+
| Alice | HR |
| Bob | Engineering |
| Charlie| NULL |
+--------+--------------+
这篇关于mysql的inner join 和left join区别的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!