MySQL UNION使用介绍及示例
- 1 用法介绍
- 2 使用示例
- 2.1 数据准备
- 2.2 查询示例
1 用法介绍
说明 | |
---|---|
作用 | UNION运算符用于组合两个或更多SELECT语句的结果集 |
使用前提 | UNION中的每个SELECT语句必须具有相同的列数 1. 这些列的数据类型必须兼容:类型不必完全相同,但是必须可以隐式转换。 2. 每个SELECT语句中的列也必须以相同的顺序排列 |
UNION 语法 | SELECT column_name(s) FROM table1 UNION SELECT column_name(s) FROM table2; |
UNION ALL语法 | SELECT column_name(s) FROM table1 UNION ALL SELECT column_name(s) FROM table2; |
UNION 和 UNION ALL区别 | union 会自动压缩多个结果集合中的重复结果,而 union all 则将所有的结果全部显示出来,不管是不是重复 |
2 使用示例
2.1 数据准备
- 测试数据库表:test_onion
- 数据库数据:
2.2 查询示例
-
假定查询需求:查找各部门男生人数和女生人数,即结果列为部门名称、男生人数、女生人数
-
查询各部门男生人数:
SELECT
org_name, count(user_sex) as man_num
FROM
test_union
where user_sex = '男'
GROUP BY org_name;
- 查询各部门女生人数:
SELECT
org_name, count(user_sex) as woman_num
FROM
test_union
where user_sex = '女'
GROUP BY org_name;
- 将两次的结果整合:
SELECT
org_name,
man_num,
woman_num
FROM
(
SELECT
org_name,
count(user_sex) AS man_num,
'' AS woman_num
FROM
test_union
WHERE
user_sex = '男'
GROUP BY
org_name
UNION ALL
SELECT
org_name,
'' AS man_num,
count(user_sex) AS woman_num
FROM
test_union
WHERE
user_sex = '女'
GROUP BY
org_name
) c
整合结果如下:
但是,如上结果可以看到,两部分数据是完全拼接的,理想的结果是同一个部门的男女数据在一条查询结果上,修改后如下:
SELECT
org_name,
SUM(man_num) as man_num,
SUM(woman_num) as woman_num
FROM
(
SELECT
org_name,
count(user_sex) AS man_num,
'' AS woman_num
FROM
test_union
WHERE
user_sex = '男'
GROUP BY
org_name
UNION ALL
SELECT
org_name,
'' AS man_num,
count(user_sex) AS woman_num
FROM
test_union
WHERE
user_sex = '女'
GROUP BY
org_name
) c
GROUP BY org_name