語法
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