在您要使用的所有表中,列的数量和顺序应该相同。 数据类型必须与每个选择查询的相应位置兼容。 在不同的 SELECT 查询中选择的列名必须具有相同的顺序。
语法格式
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: 可选,返回所有结果集,包含重复数据。
Union 与 Join 的区别
演示数据库
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.runoon.com/ | 4689 | CN |
| 4 | 微博 | http://weibo.com/ | 20 | CN |
| 5 | Facebook | https://www.facebook.com/ | 3 | USA |
| 7 | stackoverflow| http://stackoverflow.com/ | 0 | IND |
+----+---------------+---------------------------+-------+---------+
mysql> SELECT * FROM apps;
+----+------------+-------------------------+---------+
| id | app_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)
SQL UNION 实例
SELECT country FROM Websites
UNION
SELECT country FROM apps ORDER BY country;
mysql> SELECT country FROM websites UNION SELECT country FROM apps ORDER BY country;
+---------+
| country |
+---------+
| CN |
| IND |
| USA |
+---------+
3 rows in set (0.00 sec)
SQL UNION ALL 实例
SELECT country FROM Websites
UNION ALL
SELECT country FROM apps ORDER BY 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 |
+---------+
9 rows in set (0.00 sec)
带有 WHERE 的 SQL UNION ALL
SELECT country, name FROM websites
WHERE country='CN'
UNION ALL
SELECT country, app_name FROM apps
WHERE country='CN'
ORDER BY country;
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 | 淘宝 APP |
| CN | 淘宝 |
| CN | QQ APP |
| CN | 奔月教程 |
| CN | 微博 APP |
+---------+--------------+
6 rows in set (0.00 sec)

长按二维码关注公众号,查阅更多教程
文章转载自跟谁学编程,如果涉嫌侵权,请发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。





