MySQL实现7种 SQL JOINS

MySQL实现7种 SQL JOINS

文章目录

  • MySQL实现7种 SQL JOINS
    • UNION 和 UNION ALL 关键字使用
    • 7种SQL JOIN 实现

UNION 和 UNION ALL 关键字使用


MySQL在实现满外连接的时候,并不能像Oracle一样直接使用FULL OUTER JOIN,因此需要使用 UNIONUNION ALL 两个关键字,UNIONUNION ALL 使用语法如下

SELECT column, .... from table1
UNION [ALL]
SELECT column, .... from table2

UNION操作符

MySQL实现7种 SQL JOINS_第1张图片

UNION 操作符返回两个查询的结果集的并集,去除重复记录。


UNION ALL操作符

MySQL实现7种 SQL JOINS_第2张图片

UNION ALL操作符返回两个查询的结果集的并集。对于两个结果集的重复部分,不去重。

注意:执行UNION ALL语句时所需要的资源比UNION语句少。如果明确知道合并数据后的结果数据 不存在重复数据,或者不需要去除重复的数据,则尽量使用UNION ALL语句,以提高数据查询的效率。

7种SQL JOIN 实现


数据库在进行多表查询的时候,应该会有以下七种JOIN情况如下图所示

MySQL实现7种 SQL JOINS_第3张图片

MySQL具体实现案例如下

创建一张员工表和一张部门表,表结构如图

员工表

MySQL实现7种 SQL JOINS_第4张图片

部门表

MySQL实现7种 SQL JOINS_第5张图片

实现连接的SQL

## 中图 内连接
SELECT employee_id,department_name
FROM employees e JOIN departments d
ON e.department_id = d.department_id

## 左上图 左外连接
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.department_id = d.department_id

# 右上图 右外连接
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.department_id = d.department_id

## 左中图 
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.department_id = d.department_id
WHERE d.department_id IS NULL

## 右中图
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.department_id = d.department_id
WHERE e.department_id IS NULL

## 左下图: 满外连接
# 方式1: 左上图 UNION ALL 右中图
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.department_id = d.department_id
UNION ALL
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.department_id = d.department_id
WHERE e.department_id IS NULL

# 方式2: 左中图 UNION ALL 右上图
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.department_id = d.department_id
WHERE d.department_id IS NULL
UNION ALL
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.department_id = d.department_id

# 方式3 左上图 UNION 右上图 (不推荐使用 UNION,效率低)
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.department_id = d.department_id
UNION
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.department_id = d.department_id

## 右下图 左中图 UNION ALL 右中图
SELECT employee_id,department_name
FROM employees e LEFT JOIN departments d
ON e.department_id = d.department_id
WHERE d.department_id IS NULL
UNION ALL
SELECT employee_id,department_name
FROM employees e RIGHT JOIN departments d
ON e.department_id = d.department_id
WHERE e.department_id IS NULL

你可能感兴趣的:(mysql,sql)