创建一个测试数据表

CREATE TABLE `temp_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`endtime` int(10) NOT NULL,
`basic_sort` smallint(8) NOT NULL,
`type` tinyint(1) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

对UNION 和UNION ALL 进行比较:

在MySQL 5.1中文手册中有下面一句话:

如果您对UNION不使用关键词ALL,则所有返回的行都是唯一的,如同您已经对整个结果集合使用了DISTINCT。如果您指定了ALL,您会从所有用过的SELECT语句中得到所有匹配的行。

插入测试数据:

INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('a', '1534349307', '10', '2');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('a', '1534349308', '14', '2');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('c', '1534349309', '12', '1');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('d', '1534349310', '12', '1');

(SELECT id,name,endtime,basic_sort,type from temp_table where type=1)
UNION
(SELECT id,name,endtime,basic_sort,type from temp_table where type=2);
(SELECT id,name,endtime,basic_sort,type from temp_table where type=1)
UNION ALL
(SELECT id,name,endtime,basic_sort,type from temp_table where type=2);

对于上面两句分别是UNION和UNION ALL组合,但是得到的结果是一致的。

其实上面说的【所有返回的行都是唯一的】这里所说的是主键唯一:

(SELECT id,name,endtime,basic_sort,type from temp_table)
UNION
(SELECT id,name,endtime,basic_sort,type from temp_table);

(SELECT id,name,endtime,basic_sort,type from temp_table)
UNION ALL
(SELECT id,name,endtime,basic_sort,type from temp_table);

这里对于UNION返回的结果相当于对主键做一次DISTINCT,而UNION ALL 返回的结果相当于是单纯把结果查询出来然后合并返回。

对UNION查询结果进行排序:

插入测试数据(将刚刚的表内容删减,使用TRUNCATE `temp_table`):

INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('a', '1534349307', '10', '2');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('b', '1534349308', '14', '2');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('c', '1534349309', '12', '2');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('d', '1534349310', '12', '2');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('e', '1534349311', '18', '2');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('f', '1534349312', '18', '2');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('aa', '1534349313', '11', '1');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('bb', '1534349314', '11', '1');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('cc', '1534349315', '13', '1');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('dd', '1534349316', '12', '1');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('ee', '1534349317', '12', '1');
INSERT INTO `temp_table` (`name`,`endtime`,`basic_sort`,`type`) VALUES ('ff', '1534349318', '15', '1');

这里我们想要得到的结果是:按type的正序排序,接着按basic_sort倒叙排序

(select * from temp_table where type=1 ORDER BY basic_sort desc)
union
(select * from temp_table where type=2 ORDER BY basic_sort desc)

对于这样的SQL语句得到的结果是:

与没有在子句中使用ORDER BY的结果一致。

(select * from temp_table where type=1) union (select * from temp_table where type=2)

在MySQL 5.1中文手册中有下面两句话:

1、如果您想使用ORDER BY或LIMIT子句来对全部UNION结果进行分类或限制,则应对单个地SELECT语句加圆括号,并把ORDER BY或LIMIT放到最后一个的后面。

如果要完成上面的需求应该是:

(select *,type as sort_type,basic_sort as sort_value from temp_table)
union
(select *,type as sort_type,basic_sort as sort_value from temp_table)
order by sort_type ASC,sort_value ASC

2、圆括号中用于单个SELECT语句的ORDER BY只有当与LIMIT结合后,才起作用。否则,ORDER BY被优化去除。

(select * from temp_table WHERE type=1 ORDER BY basic_sort ASC LIMIT 6)
union
(select * from temp_table WHERE type=2 ORDER BY basic_sort ASC LIMIT 6)

关于这里是可以使用ORDER BY 与LIMIT 共同完成,但是有些时候我们不能在里面用LIMIT 只能在外面用,比如我们做分页,我们并不知道应该在里面LIMIT 多少才对。

下面这里有个奇怪的需求,我们需要得到下面一个这个列表,首先是按type正序排列,当type为1的时候是按照basic_sort进行正序排列,当type为2的时候按endtime倒叙排列。

因为对于type为1的时候我们不需要对endtime进行排序所以我们在type为1的时候设置endtime的值为0,对于type为2的时候我们不需要basic_sort的值进行排序,所以设置basic_sort的值为0。

(SELECT id,name,endtime,basic_sort,basic_sort as sort_basic_sort,0 as sort_endtime,type,type as sort_type FROM temp_table WHERE type=1)
union
(SELECT id,name,endtime,basic_sort,0 as sort_basic_sort,endtime as sort_endtime,type,type as sort_type FROM temp_table WHERE type=2)
ORDER BY sort_type ASC,sort_basic_sort ASC,sort_endtime DESC

关于union的一些问题的更多相关文章

  1. SQL Server-聚焦UNIOL ALL/UNION查询(二十三)

    前言 本节我们来看看有关查询中UNION和UNION ALL的问题,简短的内容,深入的理解,Always to review the basics. 初探UNION和UNION ALL 首先我们过一遍 ...

  2. SQL 提示介绍 hash/merge/concat union

    查询提示一直是个很有争议的东西,因为他影响了sql server 自己选择执行计划.很多人在问是否应该使用查询提示的时候一般会被告知慎用或不要使用...但是个人认为善用提示在不修改语句的条件下,是常用 ...

  3. LINQ to SQL语句(8)之Concat/Union/Intersect/Except

    适用场景:对两个集合的处理,例如追加.合并.取相同项.相交项等等. Concat(连接) 说明:连接不同的集合,不会自动过滤相同项:延迟. 1.简单形式: var q = ( from c in db ...

  4. SQLServer-----Union,Union All的使用方法

    转载: http://blog.csdn.net/kiqinie/article/details/8132485 select a.Name from Material as a union sele ...

  5. 假如 UNION ALL 里面的子句 有 JOIN ,那个执行更快呢

    比如: select id, name from table1 where name = 'x' union all select id, name from table2 where name =  ...

  6. sql union和union all的用法及效率

    UNION指令的目的是将两个SQL语句的结果合并起来.从这个角度来看, 我们会产生这样的感觉,UNION跟JOIN似乎有些许类似,因为这两个指令都可以由多个表格中撷取资料. UNION的一个限制是两个 ...

  7. 【oracle】union、union all、intersect、minus 的用法及区别

    一.union与union all 首先建两个view create or replace view test_view_1 as as c from dual union as c from dua ...

  8. sql with as union all

    WITH RPL (FId,Fname,Forder) AS ( SELECT ment.deptno,ment.deptname,ment.orderno FROM JTERP..fg_depart ...

  9. Oracle 中 union 和union all 的简单使用说明

    1.刚刚工作不久,经常接触oracle,但是对oracle很多东西都不是很熟.今天我们来了解一下union和union all的简单使用说明.Union(union all): 指令的目的是将两个 S ...

  10. LINQ系列:LINQ to SQL Concat/Union

    1. Concat 单列Concat var expr = (from p in context.Products select p.ProductName) .Concat( from c in c ...

随机推荐

  1. spring boot(10) 基础学习内容

    A Spring boot(10) 基础学习内容 B SpringBoot(16) 基础学习内容

  2. CONCAT substr group_concat find_in_set

    (SELECT p.*,(SELECT CONCAT(m.name,m.id) FROM service_fastfix_category m WHERE m.id=SUBSTR(p.id,1,4)) ...

  3. 解决Django Rest Framework中的跨域问题

    方案一: 全局配置 自定义中间件 # my_md.py class MiddlewareMixin(object): def __init__(self, get_response=None): se ...

  4. es6-Iterator与for...of

    Iterator(遍历器)的概念 JavaScript原有的表示“集合”的数据结构,主要是数组(Array)和对象(Object),ES6又添加了Map和Set.这样就有了四种数据集合,用户还可以组合 ...

  5. js禁止浏览器页面后退功能

    js禁止浏览器页面后退功能: <script> $(function(){ ) { //防止页面后退 history.pushState(null, null, document.URL) ...

  6. [转]linux远程登入不需要密码

    如何通过一台linux ssh远程其他linux服务器时,不要输入密码,可以自动登入.提高远程效率,不用记忆各台服务器的密码. 工具/原料   ssh,ssh-keygen,scp 方法/步骤     ...

  7. OpenSSL s_server / s_client 应用实例

    netkiller openssl tls 目录[-] 12.6. s_server / s_client 12.6.1. SSL POP3 / SMTP / IMAP 12.6.2. server ...

  8. 在github中的READEME中添加图片或者动图

    在github中reademe中添加动图或者图片 将你需要展示的图片放在这个项目中的某个文件夹中,然后再reademe中这样引入 ![maze](https://github.com/GainLoss ...

  9. pat乙级1052

    输出“\”字符: cout << "\\"; 因为‘\’是转义字符,例如“\n”代表换行. 同理,printf输出“%”: printf("%%") ...

  10. appuim操作webview控件

    1.操作webview控件,在uiautomator中如下图,能定位的只有最外层的内容.就一个webview控件,查找不到里面内容 1.使用driver.getContext(),获取是否是webvi ...