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         |
+--------+--------------+
相关推荐
Zhu75812 分钟前
部署安全的pg数据库,搭配pgadmin实现web界面管理
前端·数据库·安全
spencer_tseng18 分钟前
mysqldump: Error: Binlogging on server not active
mysql·mysqldump·binlogging
她说..28 分钟前
Redis项目实战整理
数据库·redis·缓存
kyrie_sakura38 分钟前
MySQL数据库学习笔记1 -- 基础概念,sql语句
数据库·学习·mysql
凌云若寒40 分钟前
CODESOFT试用流程
linux·运维·网络·数据库·sentinel
云贝贝贝1 小时前
Oracle 运维高频 6 坑:硬日期、AUTOEXTEND、闪回、锁、FRA、双引号
运维·数据库·oracle
九月要晚安1 小时前
从数据库到湖库一体
数据库
正在走向自律1 小时前
FastGPT高并发登录故障根治方案:50人并发报错、PostgreSQL、MongoDB数据库深度优化手册
数据库·mongodb·postgresql
姜穆澜1 小时前
时空数据处理全攻略
数据库
OceanBase数据库官方博客1 小时前
深度拆解seekdb:AI Native Database 的技术架构与核心能力
数据库·人工智能·架构