`
DavyJones2010
  • 浏览: 153742 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

MySQL: Union

阅读更多

1. Union

    1) Function: Combine the result sets from two query into one single result set.

# Single result set 1
select * from stu where stu_score > 40;

# Single result set 2
select * from stu where stu_score < 35;

# Combine result sets without union
select * from stu where stu_score < 35 || stu_score > 40;

# Combine result sets with union
select * from stu where stu_score > 40 union select * from stu where stu_score < 35;

     2) Compliance of Union

# The column number of the result sets of the two queries should be the same
# But it's recommended that the structure of the two result sets be the same

     3) Usage scenario

# In the ECShop project
# Comments are stored in two tables: 1) comment[For common comment] 2) feedback[For problem argue]
# The structure of the two tables are not that same.
# But the compliance is that the result set of the two queries should be the same.
# But in the message panel we need to see all the two types' comment. So it's best to use union instead of using two SQL statements and then combine the data in java/php/c code.

2. An example for exmplaining the usage of union

#1. Table ta
select * from ta;
+----+-----+
| id | num |
+----+-----+
| a  |   5 |
| b  |  10 |
| c  |  15 |
| d  |  10 |
+----+-----+

#2. Table tb
select * from tb;
+----+-----+
| id | num |
+----+-----+
| b  |   5 |
| c  |  10 |
| d  |  20 |
| e  |  99 |
+----+-----+

#3. Union result of the two tables
select * from ta union select * from tb;
+----+-----+
| id | num |
+----+-----+
| a  |   5 |
| b  |  10 |
| c  |  15 |
| d  |  10 |
| b  |   5 |
| c  |  10 |
| d  |  20 |
| e  |  99 |
+----+-----+

#4. Combine the num whose id are the same
select id, sum(num) from (select * from ta union select * from tb) as temp group by id;
+----+----------+
| id | sum(num) |
+----+----------+
| a  | 5        |
| b  | 15       |
| c  | 25       |
| d  | 30       |
| e  | 99       |
+----+----------+

3. A pitfall when using union

# 1. Table ta
select * from ta;
+----+-----+
| id | num |
+----+-----+
| a  |   5 |
| b  |  10 |
| c  |  15 |
| d  |  10 |
+----+-----+

# 2. Table tb
select * from tb;
+----+-----+
| id | num |
+----+-----+
| b  |   5 |
| c  |  15 |
| d  |  20 |
| e  |  99 |
+----+-----+

# 3. Union result
select * from ta union select * from tb;
+----+-----+
| id | num |
+----+-----+
| a  |   5 |
| b  |  10 |
| c  |  15 |
| d  |  10 |
| b  |   5 |
| d  |  20 |
| e  |  99 |
+----+-----+

# Pay attention to the row whose id = c;
# When ta.id == tb.id && ta.num == tb.num <Every column on current row are the same value>
# Then the union result will combine the two rows together to reduce redundancy;
# We can use key word union all instead of union to suppress auto combination.

select * from ta union all select * from tb;
+----+-----+
| id | num |
+----+-----+
| a  |   5 |
| b  |  10 |
| c  |  15 |
| d  |  10 |
| b  |   5 |
| c  |  15 |
| d  |  20 |
| e  |  99 |
+----+-----+

4. Another pitfall when using union

# 1. Common pitfall
select * from ta order by id desc union all select * from tb order by id desc;
ERROR 1221 : Incorrect usage of UNION and ORDER BY

# 2. Reason
# Because union all don't know how to order the two result set.

# 3. Solution: Add () to separate two result set to eliminate ambiguity.
# But that wouldn't affect the order of the final result. Ordered result set a union order result b, the result wouldn't be ordered even in each sub-result-set
# It's recommanded using order by or limit at the end of the final result set.
## Not recommanded:
(select * from ta order by id desc) union all (select * from tb order by id desc);
## Recommanded:
(select * from ta) union all (select * from tb) order by id desc;

# Comment:
(select * from ta order by id desc limit 4) union all (select * from tb order by id desc limit 5);
# It works!

# Reason:
# It's pointless union two ordered result set who is ordered wihout any purpose. Then it would be optimized by compiler saying order is useless in each sub-result-set.
# It's better practice union two ordered result set who is ordered with specific purpose. Such as get the largest three id or smallest three id. It wouldn't be optimized by compiler.

 

Comments:

    1) The column name of the SQL result are not forced to be the same. But the type of the column should be the same. And the result of the union operation, the name of the column is set as the left table's column name.

    2) In the previous example, if table ta's id column is primary key for ta table and if table tb's id column is primary key for tb table. When we union the two table there would be no error occurs. Because the result is just a result set (virtual table) not a real table whose id mustn't be duplicated.

分享到:
评论

相关推荐

    MySQL中使用or、in与union all在查询命令下的效率对比

    在MySQL数据库中,进行数据查询时,我们经常需要使用到`OR`、`IN`和`UNION ALL`这些操作符。这些操作符在不同的场景下有不同的效率表现,但并不是像网络上普遍认为的那样,`UNION ALL`总是比`OR`和`IN`更快。实际上...

    MySQL中union和order by同时使用的实现方法

    MySQL中union和order by是可以一起使用的,但是在使用中需要注意一些小问题,下面通过例子来说明。首先看下面的t1表。 1、如果直接用如下sql语句是会报错:Incorrect usage of UNION and ORDER BY。 SELECT * FROM ...

    MySQL UNION 与 UNION ALL 语法与用法.docx

    MySQL UNION 与 UNION ALL 语法与用法 MySQL UNION 语法用于把来自多个 SELECT 语句的结果组合到一个结果集合中。其语法格式为:SELECT column,... FROM table1 UNION[ALL] SELECT column,... FROM table2...其中,...

    MySQL:常用基本SQL语句小结

    - `UNION`:合并两个或更多`SELECT`语句的结果集。 - `JOIN`:连接两个或更多表,例如`INNER JOIN`, `LEFT JOIN`, `RIGHT JOIN`, `FULL OUTER JOIN`。 3. 子查询: 在主查询中嵌套一个查询,用子查询结果作为主查询...

    MySQL: Data Join

    在MySQL中,由于不直接支持全联接,通常通过UNION或UNION ALL结合左右联接来实现类似的效果。 在实际应用中,数据联接可以变得非常复杂,涉及多表和多条件。SQL_fiddle是一个在线的SQL练习和测试工具,`sql_join_...

    MySQL的or、in、union与索引优化

    ### MySQL的or、in、union与索引优化 在数据库查询优化中,索引的使用至关重要,它能显著提升查询速度。本文将基于一个具体的业务场景来探讨在MySQL中使用`union all`、`in`、`or`以及负向查询(如`!=`)时如何有效...

    MySQL Union合并查询数据及表别名、字段别名用法分析

    本文实例讲述了MySQL Union合并查询数据及表别名、字段别名用法。分享给大家供大家参考,具体如下: union关键字 SELECT s_id, f_name, f_price FROM fruits WHERE f_price &lt; 9.0 UNION ALL SELECT s_id, f_name...

    数据库MySQL-union(联合)

    在MySQL数据库中,`UNION` 是一种用于合并多个`SELECT`语句结果集的工具。这个操作的主要目的是将不同的查询结果集拼接在一起,形成一个新的结果集,它有效地消除了重复行。在本例中,我们将深入探讨`UNION`的使用、...

    详解MySQL中UNION的用法

    在MySQL中,`UNION` 是一种用于合并多个SELECT语句结果集的工具,它可以将来自不同表的数据组合成一个单一的结果集。`UNION` 关键字的主要目的是去除重复的行,使得最终的结果集中不包含重复记录。然而,如果你需要...

    MySQL如何使用union all获得并集排序

    在MySQL中,`UNION ALL` 用于合并多个`SELECT`语句的结果集,而这里的重点是如何在合并结果后进行排序。在给定的场景中,我们有一个文章数据表,其中文章的状态通过`PROMOTE_STATUS`字段表示,分别对应0(待发布)、...

    MySQL中UNION与UNION ALL的基本使用方法

    在MySQL中,`UNION` 和 `UNION ALL` 是用于合并多个`SELECT`语句结果的两种方式,它们在处理结果集时有着显著的区别。本文将深入探讨这两种操作符的使用方法及其性能差异。 首先,`UNION` 操作符用于合并两个或多个...

    MySQL union 语法代码示例分析

    MySQL的UNION操作符是用来合并两个或多个SELECT语句的结果集,形成一个新的单一结果集。在MySQL中,UNION主要用于合并具有相同列数和数据类型的查询结果,它可以帮助你从不同的表或者不同的查询条件中获取汇总的数据...

    浅析mysql union和union all

    MySQL中的`UNION`和`UNION ALL`是两种用于合并多个查询结果集的方法,它们在处理数据并集时有着显著的区别。 1. **UNION**: `UNION` 操作符用于合并两个或更多`SELECT`语句的结果集,并自动去除重复行。在执行`...

    Mysql联合查询UNION和Order by同时使用报错问题的解决办法

    因此,常常出现这样的错误 代码如下:select * from [IND] where INDID&gt;10unionselect * from [IND] where INDID&lt;9&gt;10 order by INDID descunionselect * from [IND] where INDID&lt;9 order by INDID desc此时就出现...

    第01篇:MySQL注入点写WebShell的5种方式1

    在盲注或报错注入的情况下,`UNION SELECT`不可用,可以利用MySQL的语句分隔符来写入WebShell。例如,通过SQLMap的`--os-shell`命令,可以实现这一目标。同样,也需要`secure_file_priv`支持,以及数据库用户的`FILE...

    Mysql联合查询UNION和UNION ALL的使用介绍

    本文详细介绍了Mysql的联合查询命令UNION和UNION ALL,总结了使用语法和注意事项,以及学习例子和项目例子,需要的朋友可以参考下

    简单了解MySQL union all与union的区别

    union 是对数据进行并集操作,不包括重复行,同时进行默认排序Union all 是对数据进行并集操作,包括重复行,不进行排序举例说明: 创建数据库表: CREATE TABLE `t_demo` ( `id` int(32) NOT NULL, `name` ...

Global site tag (gtag.js) - Google Analytics