码迷,mamicode.com
首页 > 数据库 > 详细

mysql union order by 分别排序问题

时间:2015-04-03 01:40:18      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:

两种方式:

第一种:

先各自排序,然后通过临时表嵌套再合并结果,注意排序后面必须加入 limit,否则order by不起作用

SELECT * FROM (SELECT * FROM t1 WHERE id IN (1,3,6) ORDER BY utime DESC limit 5) AS a 
UNION ALL
SELECT * FROM (SELECT * FROM t1 WHERE id IN (2,4,5) ORDER BY utime DESC limit 5) AS b
;
第二种:

通过加入临时列px查出所有结果后,再按px,utime排序

SELECT * FROM(
SELECT 0 AS px,id,NAME,utime FROM (SELECT * FROM t1 WHERE id IN (1,3,6)) AS a 
UNION ALL
SELECT  1 AS px,id,NAME,utime FROM (SELECT * FROM t1 WHERE id IN (2,4,5)  ) AS b
) AS c ORDER BY px,utime DESC


mysql union order by 分别排序问题

标签:

原文地址:http://my.oschina.net/u/1182602/blog/395348

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!