一 概述
MySQL NUION操作符用于将两个查询的结果集组合成一个结果集,同时当多个查询的结果重复时,会自动实现去重操作。
二 基本语法
select column1,column2,column3 ... from table where conditions
union [all | distinct]
select column1,column2,column3 ... from table where conditions
语法解释
-
column1,column2,column3 ...: 要检索的列。结果集以第一个查询字段名作为结果集字段名。
-
table: 要检索的数据表。
-
WHERE conditions: 可选, 检索条件。
-
DISTINCT: 可选,删除结果集中重复的数据。默认情况下 UNION 操作符已经删除了重复数据,所以 DISTINCT 修饰符对结果没啥影响。
-
ALL: 可选,返回所有结果集,包含重复数据。
注意:union前后查询的数据列数需要是一致的,否则提示
Error Code: 1222. The used SELECT statements have a different number of columns
三 简单演示
select now() nowTime
union
select current_timestamp() currentTime;
select now() nowTime
union all
select current_timestamp() currentTime;
对比可知,union默认会去除重复的值。
基本认知,如有遗漏,欢迎留言告知。谢谢