当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL UNION操作符基础知识点

MySQL UNION操作符基础知识点

2019年05月28日  | 移动技术网IT编程  | 我要评论

mysql union 操作符

本教程为大家介绍 mysql union 操作符的语法和实例。

描述

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

语法

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

演示数据库

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

下面是选自 "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.runoob.com/  | 4689 | cn   |
| 4 | 微博     | http://weibo.com/     | 20  | cn   |
| 5 | facebook   | https://www.facebook.com/ | 3   | usa   |
| 7 | stackoverflow | http://stackoverflow.com/ |  0 | ind   |
+----+---------------+---------------------------+-------+---------+

下面是 "apps" app 的数据:

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 实例

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

实例

select country from websites
union
select country from apps
order by country;

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

注释: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 输出结果如下:

带有 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 输出结果如下:

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网