您好,我是小DAI,专注于数据库管理员相关的技术问答,请问有什么可以帮您?

ad_sql__union

SQL UNION 语法


SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;

UNION 操作符默认会去除重复的记录,如果需要保留所有重复记录,可以使用 UNION ALL 操作符。

![](https://www.runoob.com/wp-content/uploads/2013/09/53e8e79b70093d886b466af8e7f71c5.png)

SQL UNION ALL 语法


SELECT column1, column2, ...
FROM table1
UNION ALL
SELECT column1, column2, ...
FROM table2;

![](https://www.runoob.com/wp-content/uploads/2013/09/SQL-UNION-ALL.png)

注释:UNION 结果集中的列名总是等于 UNION 中第一个 SELECT 语句中的列名。

演示数据库

在本教程中,我们将使用 RUNOOB 样本数据库。

下面是选自 "Websites" 表的数据:


mysql> SELECT * FROM Websites;
+----+--------------+---------------------------+-------+---------+
+----+--------------+---------------------------+-------+---------+
<table>
<tr>
<th>1</th>
<th>Google</th>
<th>https://www.google.cm/</th>
<th>1</th>
<th>USA</th>
</tr>
<tr>
<td>3</td>
<td>菜鸟教程</td>
<td>http://www.runoob.com/</td>
<td>4689</td>
<td>CN</td>
</tr>
<tr>
<td>4</td>
<td>微博</td>
<td>http://weibo.com/</td>
<td>20</td>
<td>CN</td>
</tr>
<tr>
<td>5</td>
<td>Facebook</td>
<td>https://www.facebook.com/</td>
<td>3</td>
<td>USA</td>
</tr>
<tr>
<td>7</td>
<td>stackoverflow</td>
<td>http://stackoverflow.com/</td>
<td>0</td>
<td>IND</td>
</tr>
</table>

+----+---------------+---------------------------+-------+---------+

下面是 "apps" APP 的数据:


mysql> SELECT * FROM apps;
+----+------------+-------------------------+---------+
+----+------------+-------------------------+---------+
<table>
<tr>
<th>1</th>
<th>QQ APP</th>
<th>http://im.qq.com/</th>
<th>CN</th>
</tr>
<tr>
<td>3</td>
<td>淘宝 APP</td>
<td>https://www.taobao.com/</td>
<td>CN</td>
</tr>
</table>

+----+------------+-------------------------+---------+
3 rows in set (0.00 sec)

SQL UNION 实例

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

实例


SELECT country FROM Websites
UNION
SELECT country FROM apps
ORDER BY country;

执行以上 SQL 输出结果如下:

![](https://www.runoob.com/wp-content/uploads/2013/09/union1.jpg)

注释:UNION 不能用于列出两个表中所有的country。如果一些网站和APP来自同一个国家,每个国家只会列出一次。UNION 只会选取不同的值。请使用 UNION ALL 来选取重复的值!

SQL UNION ALL 实例

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

实例


SELECT country FROM Websites
UNION ALL
SELECT country FROM apps
ORDER BY country;

执行以上 SQL 输出结果如下:

![](https://www.runoob.com/wp-content/uploads/2013/09/union2.jpg)

带有 WHERE 的 SQL UNION ALL

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

实例


SELECT country, name FROM Websites
WHERE country='CN'
UNION ALL
SELECT country, app_name FROM apps
WHERE country='CN'
ORDER BY country;

执行以上 SQL 输出结果如下:

![](https://www.runoob.com/wp-content/uploads/2013/09/AAA99C7B-36A5-43FB-B489-F8CE63B62C71.jpg)

来源:https://www.runoob.com/sql/sql-union.html