MySQL UNION 操作符
mysql union 操作符
mysql union 操作符用于合并兩個(gè)或多個(gè) select 語(yǔ)句的結(jié)果集,結(jié)果集中的同一記錄只保留一條。union 類似于數(shù)學(xué)里的合集。
mysql union all 可以選取重復(fù)的值。
請(qǐng)注意,union 內(nèi)部的 select 語(yǔ)句必須擁有相同數(shù)量的列。列也必須擁有相似的數(shù)據(jù)類型。同時(shí),每條 select 語(yǔ)句中的列的順序必須相同。
1. mysql union 操作符的語(yǔ)法
select expression1, expression2, ... expression_n from tables [where conditions] union [all | distinct] select expression1, expression2, ... expression_n from tables [where conditions];
參數(shù)
expression1, expression2, ... expression_n: 要檢索的列。
tables: 要檢索的數(shù)據(jù)表。
where conditions: 可選, 檢索條件。
distinct: 可選,刪除結(jié)果集中重復(fù)的數(shù)據(jù)。默認(rèn)情況下 union 操作符已經(jīng)刪除了重復(fù)數(shù)據(jù),所以 distinct 修飾符對(duì)結(jié)果沒啥影響。
all: 可選,返回所有結(jié)果集,包含重復(fù)數(shù)據(jù)。
2. mysql union 操作符范例
我們將使用 yapf 樣本數(shù)據(jù)庫(kù)中 websites 表的數(shù)據(jù):
mysql> select * from websites; +----+--------------+---------------------------+-------+---------+ | id | name | url | alexa | country | +----+--------------+---------------------------+-------+---------+ | 1 | google | https://www.google.cm/ | 1 | usa | | 2 | 淘寶 | https://www.taobao.com/ | 13 | cn | | 3 | 碩編程 | http:/// | 4689 | cn | | 4 | 微博 | http://weibo.com/ | 20 | cn | | 5 | facebook | https://www.facebook.com/ | 3 | usa | | 6 | stackoverflow | http://stackoverflow.com/ | 0 | ind | +----+---------------+---------------------------+-------+---------+
下面是 "apps" app 的數(shù)據(jù):
mysql> select * from apps; +----+------------+-------------------------+---------+ | id | name | url | country | +----+------------+-------------------------+---------+ | 1 | qq app | http://im.qq.com/ | cn | | 2 | 微博 app | http://weibo.com/ | cn | | 3 | 淘寶 app | https://www.taobao.com/ | cn | +----+------------+-------------------------+---------+ 3 rows in set (0.00 sec)
1)sql union 范例
下面的 sql 語(yǔ)句從 "websites" 和 "apps" 表中選取所有不同的country(只有不同的值):
mysql 范例
select country from websites
union
select country from apps
order by country;
union
select country from apps
order by country;