[关闭]
@yanglt7 2018-06-06T06:37:05.000000Z 字数 2193 阅读 871

4 MySQL UNION操作符

MySQL


描述

MySQL UNION 操作符用于连接两个以上的 SELECT 语句的结果组合到一个结果集合中。多个 SELECT 语句会删除重复的数据。

语法

MySQL UNION 操作符语法格式:

  1. SELECE expression1,expression2,...expression_n
  2. FROM tables
  3. [WHERE conditions]
  4. UNION [ALL|DISTINCT]
  5. SELECT expression1,expression2,...expression_n
  6. FROM tables
  7. [WHERE conditions];

参数

演示数据库

  1. mysql> use test;
  2. Database changed
  3. mysql> select * from Websites;
  4. +------+---------------+--------------------------------+-------+---------+
  5. | id | name | url | alexa | country |
  6. +------+---------------+--------------------------------+-------+---------+
  7. | 2 | 淘宝 | https://www.taobao.com/ | 13 | CN |
  8. | 3 | 菜鸟教程 | https://www.runoob.com/ | 4689 | CN |
  9. | 4 | 微博 | https://www.weibo.com/ | 20 | CN |
  10. | 5 | Facebook | https://www.facebook.com/ | 3 | USA |
  11. | 7 | stackoverflow | https://www.stackoverflow.com/ | 0 | IND |
  12. | 1 | Google | https://www.google.com/ | 1 | USA |
  13. +------+---------------+--------------------------------+-------+---------+
  14. mysql> select * from apps;
  15. +----+------------+-------------------------+---------+
  16. | id | app_name | url | country |
  17. +----+------------+-------------------------+---------+
  18. | 2 | QQ APP | https://www.im.qq.com/ | CN |
  19. | 3 | 微博 APP | https://www.weibo.com/ | CN |
  20. | 4 | 淘宝 APP | https://www.taobao.com/ | CN |
  21. +----+------------+-------------------------+---------+

SQL UNION 实例

1.下面的 SQL 语句从 "Websites" 和 "apps" 表中选取所有不同的country(只有不同的值):

  1. mysql> select country from Websites
  2. -> union
  3. -> select country from apps
  4. -> order by country;
  5. +---------+
  6. | country |
  7. +---------+
  8. | CN |
  9. | IND |
  10. | USA |
  11. +---------+

注释:UNION 不能用于列出两个表中所有的country。如果一些网站和APP来自同一个国家,每个国家只会列出一次。UNION 只会选取不同的值。请使用 UNION ALL 来选取重复的值!
2.下面的 SQL 语句使用 UNION ALL 从 "Websites" 和 "apps" 表中选取所有的country(也有重复的值):

  1. mysql> select country from Websites
  2. -> union all
  3. -> select country from apps
  4. -> order by country;
  5. +---------+
  6. | country |
  7. +---------+
  8. | CN |
  9. | CN |
  10. | CN |
  11. | CN |
  12. | CN |
  13. | CN |
  14. | IND |
  15. | USA |
  16. | USA |
  17. +---------+

带有WHERE的SQL UNION ALL

下面的 SQL 语句使用 UNION ALL 从 "Websites" 和 "apps" 表中选取所有的中国(CN)的数据(也有重复的值):

  1. mysql> select country,name from Websites
  2. -> WHERE country='CN'
  3. -> union all
  4. -> select country,app_name from apps
  5. -> WHERE country='CN'
  6. -> order by country;
  7. +---------+--------------+
  8. | country | name |
  9. +---------+--------------+
  10. | CN | 淘宝 |
  11. | CN | 菜鸟教程 |
  12. | CN | 微博 |
  13. | CN | QQ APP |
  14. | CN | 微博 APP |
  15. | CN | 淘宝 APP |
  16. +---------+--------------+
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注