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         |
+--------+--------------+
相关推荐
ClouGence6 分钟前
SQL Server CDC 能放到 Always On 备库读吗?一文讲透原理与实践
数据库·sql server
先吃饱再说17 小时前
存储的进化:从 MySQL 到浏览器缓存,数据到底住在哪?
数据库
Nturmoils17 小时前
字段太多看不全,ksql 的展开模式和输出控制怎么用
数据库·后端
Databend20 小时前
Agent 轨迹分析与归因的数据工程实践
大数据·数据库·agent
这个DBA有点耶20 小时前
SQL改写进阶:标量子查询的“隐形代价”与消除实战
数据库·mysql·架构
smallyoung21 小时前
数据库乐观锁深度解析:MySQL、PostgreSQL 实战 + Spring Boot 集成指南
数据库·mysql·postgresql
parade岁月21 小时前
MySQL JOIN解析:朴实无华但食之有味
数据库·后端
用户3169353811831 天前
MySQL服务无法启动问题解决全记录
数据库
vivo互联网技术1 天前
从 10 分钟到 1 秒:ES 深度分页任意跳页的三轮优化实战
服务器·数据库·redis·elasticsearch·深度分页
数据技术说1 天前
MySQL 迁移实战——如何实现真正的"零改造"平滑切换
mysql