使用UNION语句进行双重ORDER BY排序

时间:2012-09-04 21:18:01

标签: mysql sql

(
SELECT * 
FROM (

SELECT d
FROM myTable
WHERE id =  "4h"
AND d <  "2011-12-08 12:00:00"
ORDER BY d DESC 
LIMIT 10
)tmp
ORDER BY d ASC
)
UNION (

SELECT d
FROM myTable
WHERE id =  "4h"
AND d >=  "2011-12-08 12:00:00"
ORDER BY d ASC 
LIMIT 10
)

我正在尝试使用两个SELECT语句和一个UNION来获取特定ID之前和之后的10个结果。第一个SELECT使用ORDER BY DESC获取前10个,然后我尝试在第二个ORDER BY ASC中包含该信息,以ASC顺序获取所有结果但由于某种原因不起作用。

以下是我目前得到的结果:

d
2011-12-08 08:00:00
2011-12-08 04:00:00
2011-12-08 00:00:00
2011-12-07 20:00:00
2011-12-07 16:00:00
2011-12-07 12:00:00
2011-12-07 08:00:00
2011-12-07 04:00:00
2011-12-07 00:00:00
2011-12-06 20:00:00 <- These top 10 results should ASC!
2011-12-08 12:00:00
2011-12-08 16:00:00
2011-12-08 20:00:00
2011-12-09 00:00:00
2011-12-09 04:00:00
2011-12-09 08:00:00
2011-12-09 12:00:00
2011-12-09 16:00:00
2011-12-09 20:00:00
2011-12-11 20:00:00

这就是我想要的:

d
2011-12-06 20:00:00
2011-12-07 00:00:00
2011-12-07 04:00:00
2011-12-07 08:00:00
2011-12-07 12:00:00
2011-12-07 16:00:00
2011-12-07 20:00:00
2011-12-08 00:00:00
2011-12-08 04:00:00
2011-12-08 08:00:00
2011-12-08 12:00:00
2011-12-08 16:00:00
2011-12-08 20:00:00
2011-12-09 00:00:00
2011-12-09 04:00:00
2011-12-09 08:00:00
2011-12-09 12:00:00
2011-12-09 16:00:00
2011-12-09 20:00:00
2011-12-11 20:00:00

1 个答案:

答案 0 :(得分:2)

(
  SELECT   d
  FROM     myTable
  WHERE    id = '4h' AND d <  '2011-12-08 12:00:00'
  ORDER BY d DESC
  LIMIT    10
) UNION ALL (  
  SELECT   d
  FROM     myTable
  WHERE    id = '4h' AND d >= '2011-12-08 12:00:00'
  ORDER BY d ASC
  LIMIT    10
)
ORDER BY d ASC