MySQL UNION 操作符

mysql union 操作符

mysql union 操作符用于合并两个或多个 select 语句的结果集,结果集中的同一记录只保留一条。union 类似于数学里的合集。

mysql union all 可以选取重复的值。

请注意,union 内部的 select 语句必须拥有相同数量的列。列也必须拥有相似的数据类型。同时,每条 select 语句中的列的顺序必须相同。

 

1. mysql union 操作符的语法

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: 可选,返回所有结果集,包含重复数据。

 

2. mysql union 操作符范例

我们将使用 yapf 样本数据库中 websites 表的数据:

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://www.yapf.com/    | 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 的数据:

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 语句从 "websites" 和 "apps" 表中选取所有不同的country(只有不同的值):

mysql 范例

select country from websites
union
select country from apps
order by country;
相关文章