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         |
+--------+--------------+
相关推荐
weixin_4597539411 小时前
golang如何实现Trace上下文传播_golang Trace上下文传播实现思路
jvm·数据库·python
weixin_4440129311 小时前
PHP 中逻辑或(--)运算符的正确使用与条件逻辑重构指南
jvm·数据库·python
iAm_Ike17 小时前
Go 中自定义类型与基础类型间的显式类型转换详解
jvm·数据库·python
iuvtsrt17 小时前
Golang怎么实现方法集与接口的匹配_Golang如何理解值类型和指针类型实现接口的区别【详解】
jvm·数据库·python
tongluowan00718 小时前
MySQL中列数量及长度
数据库·mysql
-liming-19 小时前
单片机设计_串口调试工具
数据库·单片机·mongodb
鹿角片ljp19 小时前
从告警检测到智能研判:SQL 注入研判模型的设计与实践
数据库·sql
小新同学^O^20 小时前
简单学习 --> Spring事务
数据库·学习·spring
前进的李工20 小时前
MySQL慢查询日志优化实战
数据库·mysql·性能优化
KaMeidebaby21 小时前
卡梅德生物技术快报|禽类成纤维细胞 FISH 实验:鸟类性别染色体基因定位技术实现与数据验证
前端·数据库·其他·百度·新浪微博