mysql的inner join 和left join区别

1. INNER JOIN

INNER JOIN 只返回两个表中满足连接条件的匹配行。换句话说,它只返回那些在连接的两个表中都有匹配值的行。如果某一行在其中一个表中没有匹配项,那么这行不会出现在结果集中。

写法:

sql 复制代码
SELECT columns
FROM table1
INNER JOIN table2
ON table1.column = table2.column;

假设有两个表 employees 和 departments:

bash 复制代码
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:

sql 复制代码
SELECT employees.name, departments.department
FROM employees
INNER JOIN departments
ON employees.dept_id = departments.id;

结果为:

bash 复制代码
+--------+--------------+
| name   | department   |
+--------+--------------+
| Alice  | HR           |
| Bob    | Engineering  |
+--------+--------------+

2. LEFT JOIN

LEFT JOIN 返回左表中的所有行,即使在右表中没有匹配项。在这种情况下,右表中的结果为 NULL。

用法:

sql 复制代码
SELECT columns
FROM table1
LEFT JOIN table2
ON table1.column = table2.column;

同上文中提到的表,执行以下SQL

sql 复制代码
SELECT employees.name, departments.department
FROM employees
LEFT JOIN departments
ON employees.dept_id = departments.id;

执行结果如下:

bash 复制代码
+--------+--------------+
| name   | department   |
+--------+--------------+
| Alice  | HR           |
| Bob    | Engineering  |
| Charlie| NULL         |
+--------+--------------+
相关推荐
dualven_in_csdn12 分钟前
【数据库损坏】关于一次现场数据库损坏
数据库·mysql
锦衣夜行?31 分钟前
oracle 未知长度从左到右截取某个字符串
数据库·oracle
han_hanker1 小时前
@JsonIgnore,@JsonProperty, @JsonInclude,@JsonFormat
数据库·oracle
hanyi_qwe1 小时前
MySQL事务基础
数据库·mysql
l1t1 小时前
三种用SQL解决Advent of Code 2022第8题 树顶木屋 的比较和分析
数据库·sql·oracle·duckdb·advent of code
如果未来,1 小时前
Oracle的Redo log和Undo log的区别
数据库·oracle
koping_wu1 小时前
【方案设计】Mysql相关场景
数据库·mysql
杨云龙UP1 小时前
SQL Server小技巧:用 SSMS 重置登录密码,不影响正在运行的系统
运维·服务器·数据库·sql·sqlserver
洁洁!1 小时前
openEuler多样性算力支持实践:容器化多架构应用部署与调度
服务器·数据库·科技·语言模型·数据分析
白露与泡影1 小时前
MySQL整体设计与存储引擎深度剖析:从架构哲学到引擎选型(了解)
数据库·mysql·架构