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         |
+--------+--------------+
相关推荐
Savvy..19 分钟前
Day16若依-帝可得
数据库
Java后端的Ai之路24 分钟前
【AI大模型开发】-Embedding 与向量数据库:从基础概念到实战应用
数据库·人工智能·embedding·向量数据库·ai应用开发工程师
2501_9481949827 分钟前
RN for OpenHarmony AnimeHub项目实战:关于页面开发
数据库·react native
松涛和鸣33 分钟前
DAY55 Getting Started with ARM and IMX6ULL
linux·服务器·网络·arm开发·数据库·html
huahualaly2 小时前
重建oracle测试库步骤
数据库·oracle·ffmpeg
墨香幽梦客2 小时前
数据库选型对比:MySQL、Oracle与PostgreSQL的企业应用场景分析
数据库·mysql·oracle
wei_shuo2 小时前
多模一体破局:金仓数据库引领文档数据库国产化新征程
数据库·金仓数据库
Coder_Boy_2 小时前
基于SpringAI的在线考试系统-数据库 表结构 & 完整外键依赖关系梳理
java·数据库·人工智能·软件工程
清风拂山岗 明月照大江2 小时前
MySQL进阶
数据库·sql·mysql
努力进修2 小时前
金仓数据库:多模融合内核驱动,重构国产化文档数据库新生态
数据库·重构