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         |
+--------+--------------+
相关推荐
陈天伟教授11 小时前
人工智能训练师认证教程(2)Python os入门教程
前端·数据库·python
Elastic 中国社区官方博客12 小时前
Elasticsearch:在分析过程中对数字进行标准化
大数据·数据库·elasticsearch·搜索引擎·全文检索
聪明努力的积极向上12 小时前
【MYSQL】字符串拼接和参数化sql语句区别
数据库·sql·mysql
代码or搬砖12 小时前
RBAC(权限认证)小例子
java·数据库·spring boot
神仙别闹12 小时前
基于QT(C++)实现学本科教务系统(URP系统)
数据库·c++·qt
2301_7683502312 小时前
MySQL为什么选择InnoDB作为存储引擎
java·数据库·mysql
上海蓝色星球12 小时前
迈向智慧电网新纪元:上海蓝色星球数字孪生变电主子站系统
运维·数据库
是大芒果12 小时前
数据库表设计
数据库
哥哥还在IT中12 小时前
MySQL order by 如何优化
数据库·mysql
积跬步,慕至千里12 小时前
postgre数据库大批量快速导出方法总结
数据库·postgres