请教一条关于时间排序的 sql 语句

2014-07-16 15:35:56 +08:00
 imxz
数据表中有一个字段为 start_time,储存的是Unix时间戳,值包括过去时间和未来时间,要实现的排序原则如下:
1、过去的时间按照时间戳递减排序
2、未来的时间按照未来时间戳减去现在时间戳的值递增排序

例:
现在时间是 1405495903 (2014/7/16 15:31:43)

排序前:
1405495901 1405495902 1405495904 1405495905

排序后:
1405495904 1405495905 1405495902 1405495901
2517 次点击
所在节点    问与答
6 条回复
hellojinjie
2014-07-16 15:42:05 +08:00
select start_time from table where start_time < unix_timestamp() order by start_time desc
union
select start_time from table where start_time >= unix_timestamp() order by start_time asc
caofugui
2014-07-16 15:44:43 +08:00
首先这个用SQL去操作很蛋疼,程序上用两条SQL语句不就搞定?
其次设计上本身就不合理,过去时间跟未来时间怎么能混在一起呢?
lu18887
2014-07-16 16:57:16 +08:00
@hellojinjie union正解
imxz
2014-07-16 19:45:43 +08:00
@hellojinjie 谢谢你
imxz
2014-07-17 13:22:55 +08:00
@hellojinjie 测试了一下,然后发现 order by子句必须写在最后一个结果集里,并且其排序规则将改变操作后的排序结果。 所以问题还是没有解决。。。
imxz
2014-07-17 13:50:50 +08:00
这样子就行了:

select * from (select * from `table` where `start_time` >= unix_timestamp() order by `start_time` asc)tmpa
union
select * from (select * from `table` where `start_time` < unix_timestamp() order by `start_time` desc)tmpb

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/122937

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX