美文网首页MySQL基础
union和union all 的区别

union和union all 的区别

作者: 筱筱说 | 来源:发表于2017-01-13 15:42 被阅读463次

使用union关键字时,可以给出多条select 语句,并将它们的结果合成单个结果集。合并时两个表对应的列数和数据类型必须相同,每个select 语句之间使用union或union all 关键字分隔,union 执行的时候删除重复的记录,所有返回的行都是唯一,使用union all 关键字的作用是不删除重复行也不对结果进行自动排序。

例如:

mysql> select s_id,f_name from fruits where s_id=101 union select s_id,f_name from fruits where f_price<10;
+------+------------+
| s_id | f_name     |
+------+------------+
|  101 | apple      |
|  101 | blackberry |
|  101 | cherry     |
|  103 | apricot    |
|  106 | ahfjwj     |
|  103 | cococut    |
|  102 | grape      |
+------+------------+
7 rows in set (0.00 sec)

mysql> select s_id,f_name from fruits where s_id=101 union all select s_id,f_name from fruits where f_price<10;
+------+------------+
| s_id | f_name     |
+------+------------+
|  101 | apple      |
|  101 | blackberry |
|  101 | cherry     |
|  101 | apple      |
|  103 | apricot    |
|  106 | ahfjwj     |
|  101 | cherry     |
|  103 | cococut    |
|  102 | grape      |
+------+------------+
9 rows in set (0.00 sec)

每个select集是这样的

mysql> select s_id,f_name from fruits where s_id=101;
+------+------------+
| s_id | f_name     |
+------+------------+
|  101 | apple      |
|  101 | blackberry |
|  101 | cherry     |
+------+------------+
3 rows in set (0.00 sec)

mysql> select s_id,f_name from fruits where f_price<10
    -> ;
+------+---------+
| s_id | f_name  |
+------+---------+
|  101 | apple   |
|  103 | apricot |
|  106 | ahfjwj  |
|  101 | cherry  |
|  103 | cococut |
|  102 | grape   |
+------+---------+
6 rows in set (0.00 sec)

很明显 union all 没有去重,查询的结果还有重复的行,

相关文章

  • SQL union和union all操作符

    一、union和union all区别 union会去重,union all不会去重 二、SQL union操作符...

  • SQL知识点

    0. SQL基础 inner join和left join的区别 union和union all的区别 union...

  • union与union all

    union和union all的区别是,union会自动压缩多个结果集合中的重复结果,而union all则将所有...

  • SQL面试题,快问快答!

    1. UNION ALL 与 UNION 的区别 UNION和UNION ALL关键字都是将两个结果集合并为一个。...

  • union和union all的区别

    如果我们需要将两个select语句的结果作为一个整体显示出来,我们就需要用到union或者union all关键字...

  • union和union all 的区别

    使用union关键字时,可以给出多条select 语句,并将它们的结果合成单个结果集。合并时两个表对应的列数和数据...

  • SQL [UNION]和[UNION ALL]用法

    原文链接:SQL UNION和UNION ALL用法 一、概述 union和union all都用于合并多个查询,...

  • 字节飞书后端一面凉经

    1.mybatis中#{}和¥{}区别2.union和union all区别3.redis分布锁4.Integer...

  • 数据库

    面试题5:union all 和 union的区别 Union:对两个结果集进行并集操作,不包括重复行,同时进行默...

  • union 与 union all 区别

    union all (SELECTsc.IntelUserCode,sc.StartDate,sc.EndDate...

网友评论

    本文标题:union和union all 的区别

    本文链接:https://www.haomeiwen.com/subject/fwjsbttx.html