语法

SELECT expression1, expression2, ... expression_n FROM tables
[WHERE conditions]
UNION [ALL | DISTINCT]
SELECT expression1, expression2, ... expression_n FROM tables
[WHERE conditions];

参数说明

  • expression1, expression2, ... expression_n: 要检索的列。
  • tables: 要检索的数据表。
  • WHERE conditions: 可选, 检索条件。
  • DISTINCT: 可选,删除结果集中重复的数据。默认情况下 UNION 操作符已经删除了重复数据,所以 DISTINCT 修饰符对结果没啥影响。
  • ALL: 可选,返回所有结果集,包含重复数据。

实例演示

一个登录日志表  按年分表 log_2018 log_2019 log_2020

日志表字段 id name(登录人名字) ip(ip地址) desc (登录说明)delFlag(删除状态)  at(登录时间)

 

查询2018-2020年所有的日志

select id,name,ip,desc,delFlag,at from log_2020
union all
select id,name,ip,desc,delFlag,at from log_2019 
union all
select id,name,ip,desc,delFlag,at from log_2018 
where delFlag = 0 order by at desc