UNION 和 UNION ALL 作用

联合查询 union ,union all

对于union查询,就是把多次查询的结果合并起来,形成一个新的查询结果集。

select 字段列表 from 表A ,,,

select 字段列表 from 表B .....

复制代码
查询语句1
UNION
查询语句2;

查询语句1
UNION ALL
查询语句2;

1. 最简单示例(合并两个部门查询)

sql

复制代码
select dept.id, dept.name from dept where dept.id = 1
union
select dept.id, dept.name from dept where dept.id = 2;

sql

复制代码
select dept.id, dept.name from dept where dept.id = 1
union all
select dept.id, dept.name from dept where dept.id = 2;

2. 合并不同表的结构相同数据

比如把员工姓名 和 部门姓名 放一列展示

sql

复制代码
select emp.name from emp
union
select dept.name from dept;

sql

复制代码
select emp.name from emp
union all
select dept.name from dept;

3. 多表查询 + UNION 组合

sql

复制代码
select emp.name, dept.name
from emp
inner join dept
on emp.dept_id = dept.id
where dept.name = '研发部'

union

select emp.name, dept.name
from emp
inner join dept
on emp.dept_id = dept.id
where dept.name = '市场部';
复制代码
-- 查询薪资<5000 并且年龄大于50 的员工。
select * from emp33 where salary <5000 and age>50;


-- 查询薪资低于5000 的员工,和年龄大于50 岁的员工的全部查询出来
select * from emp33 where salary <5000
union all
select * from emp33 where age>50;

union all有重复 会将全部的数据直接合并在一起,

union 会对合并之后的数据去重。

相关推荐
何以解忧,唯有..13 分钟前
数据库索引失效的常见情况与优化策略
数据库·sql·oracle
这个DBA有点耶1 小时前
分布式数据库到底该不该上?从判断标准到架构选型的实战思考
数据库·架构·dba
01_ice2 小时前
MySQL库和表的操作
数据库·mysql
布莱克6052 小时前
数据库索引分类:数据结构、物理存储与逻辑角度详解
数据结构·数据库
SelectDB2 小时前
DeepSeek Harness 接入 Litefuse:完善 Agent 可观测与评估能力
数据库
这个DBA有点耶3 小时前
从库延迟的“二次放大”效应:一次大事务,拖垮整个读写分离
数据库·mysql·架构
LearnYard4 小时前
自然语言驱动的数据图表生成:几款工具功能对比实践
数据库·百度·powerpoint
一个有温度的技术博主4 小时前
MySQL 三大日志协同机制:redo log、undo log 与 binlog 的联合运作
数据库·mysql·oracle
ltl4 小时前
ClickHouse 与 DuckDB 选型:不是同一类列存
数据库
ltl4 小时前
RocksDB WAL 与 WriteBatch:持久化与原子批写
数据库