使用union和union all合并两个或多个select语句的结果集
在mysql中, union
和 union all
是用于合并两个或多个 select 语句的结果集的操作符。
union
会去除结果集中的重复行,返回唯一的行,而 union all
会返回所有的行,包括重复行。
举个通用的例子
select column1, column2, ... from table1 where condition union select column1, column2, ... from table2 where condition;
select column1, column2, ...
: 指定要查询的列。from table
: 指定要查询的表。where condition
: 指定筛选条件(可选)。
注意事项:
union
连接的两个 select 语句必须包含相同数量和类型的列,列的顺序也必须相同。
默认情况下,union
会去除重复的行。如果要包含重复的行,可以使用 union all
。
使用 union
或 union all
时,结果集的列名是由第一个 select
语句中的列名决定的,因此要确保两个 select
语句中的列名和类型相匹配。
举个实际的例子
假设有两个表 employees1
和 employees2
包含相同的列结构和部分重复数据,然后使用 union
和 union all
进行查询和合并。
创建两个表并插入一些数据
-- 创建 employees1 表 create table employees1 ( employee_id int, first_name varchar(50), last_name varchar(50) ); -- 插入数据到 employees1 表 insert into employees1 values (1, 'john', 'doe'), (2, 'jane', 'smith'), (3, 'bob', 'johnson'), (4, 'alice', 'doe'); -- 创建 employees2 表 create table employees2 ( employee_id int, first_name varchar(50), last_name varchar(50) ); -- 插入数据到 employees2 表,包含一些与 employees1 表重复的数据 insert into employees2 values (3, 'bob', 'johnson'), (4, 'alice', 'doe'), (5, 'eva', 'williams');
使用 union
合并这两个表的数据:
-- 使用 union 合并,去除重复行 select employee_id, first_name, last_name from employees1 union select employee_id, first_name, last_name from employees2;
结果如下:
+-------------+------------+-----------+ | employee_id | first_name | last_name | +-------------+------------+-----------+ | 1 | john | doe | | 2 | jane | smith | | 3 | bob | johnson | | 4 | alice | doe | | 5 | eva | williams | +-------------+------------+-----------+
可以看到,union
自动去除了重复的行。
使用 union all
合并这两个表的数据:
-- 使用 union all 合并,包含重复行 select employee_id, first_name, last_name from employees1 union all select employee_id, first_name, last_name from employees2;
结果如下:
+-------------+------------+-----------+ | employee_id | first_name | last_name | +-------------+------------+-----------+ | 1 | john | doe | | 2 | jane | smith | | 3 | bob | johnson | | 4 | alice | doe | | 3 | bob | johnson | | 4 | alice | doe | | 5 | eva | williams | +-------------+------------+-----------+
可以看到
union all
保留了所有行,包括重复的行。
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论