@yanglt7
2018-06-06T06:37:05.000000Z
字数 2193
阅读 871
MySQL
MySQL UNION 操作符用于连接两个以上的 SELECT 语句的结果组合到一个结果集合中。多个 SELECT 语句会删除重复的数据。
MySQL UNION 操作符语法格式:
SELECE expression1,expression2,...expression_n
FROM tables
[WHERE conditions]
UNION [ALL|DISTINCT]
SELECT expression1,expression2,...expression_n
FROM tables
[WHERE conditions];
mysql> use test;
Database changed
mysql> select * from Websites;
+------+---------------+--------------------------------+-------+---------+
| id | name | url | alexa | country |
+------+---------------+--------------------------------+-------+---------+
| 2 | 淘宝 | https://www.taobao.com/ | 13 | CN |
| 3 | 菜鸟教程 | https://www.runoob.com/ | 4689 | CN |
| 4 | 微博 | https://www.weibo.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
| 7 | stackoverflow | https://www.stackoverflow.com/ | 0 | IND |
| 1 | Google | https://www.google.com/ | 1 | USA |
+------+---------------+--------------------------------+-------+---------+
mysql> select * from apps;
+----+------------+-------------------------+---------+
| id | app_name | url | country |
+----+------------+-------------------------+---------+
| 2 | QQ APP | https://www.im.qq.com/ | CN |
| 3 | 微博 APP | https://www.weibo.com/ | CN |
| 4 | 淘宝 APP | https://www.taobao.com/ | CN |
+----+------------+-------------------------+---------+
1.下面的 SQL 语句从 "Websites" 和 "apps" 表中选取所有不同的country(只有不同的值):
mysql> select country from Websites
-> union
-> select country from apps
-> order by country;
+---------+
| country |
+---------+
| CN |
| IND |
| USA |
+---------+
注释:UNION 不能用于列出两个表中所有的country。如果一些网站和APP来自同一个国家,每个国家只会列出一次。UNION 只会选取不同的值。请使用 UNION ALL 来选取重复的值!
2.下面的 SQL 语句使用 UNION ALL 从 "Websites" 和 "apps" 表中选取所有的country(也有重复的值):
mysql> select country from Websites
-> union all
-> select country from apps
-> order by country;
+---------+
| country |
+---------+
| CN |
| CN |
| CN |
| CN |
| CN |
| CN |
| IND |
| USA |
| USA |
+---------+
下面的 SQL 语句使用 UNION ALL 从 "Websites" 和 "apps" 表中选取所有的中国(CN)的数据(也有重复的值):
mysql> select country,name from Websites
-> WHERE country='CN'
-> union all
-> select country,app_name from apps
-> WHERE country='CN'
-> order by country;
+---------+--------------+
| country | name |
+---------+--------------+
| CN | 淘宝 |
| CN | 菜鸟教程 |
| CN | 微博 |
| CN | QQ APP |
| CN | 微博 APP |
| CN | 淘宝 APP |
+---------+--------------+