V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
imxz
V2EX  ›  问与答

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

  •  
  •   imxz · 2014-07-16 15:35:56 +08:00 · 2507 次点击
    这是一个创建于 3583 天前的主题,其中的信息可能已经有所发展或是发生改变。
    数据表中有一个字段为 start_time,储存的是Unix时间戳,值包括过去时间和未来时间,要实现的排序原则如下:
    1、过去的时间按照时间戳递减排序
    2、未来的时间按照未来时间戳减去现在时间戳的值递增排序

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

    排序前:
    1405495901 1405495902 1405495904 1405495905

    排序后:
    1405495904 1405495905 1405495902 1405495901
    6 条回复    2014-07-17 13:50:50 +08:00
    hellojinjie
        1
    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
        2
    caofugui  
       2014-07-16 15:44:43 +08:00
    首先这个用SQL去操作很蛋疼,程序上用两条SQL语句不就搞定?
    其次设计上本身就不合理,过去时间跟未来时间怎么能混在一起呢?
    lu18887
        3
    lu18887  
       2014-07-16 16:57:16 +08:00
    @hellojinjie union正解
    imxz
        4
    imxz  
    OP
       2014-07-16 19:45:43 +08:00
    @hellojinjie 谢谢你
    imxz
        5
    imxz  
    OP
       2014-07-17 13:22:55 +08:00
    @hellojinjie 测试了一下,然后发现 order by子句必须写在最后一个结果集里,并且其排序规则将改变操作后的排序结果。 所以问题还是没有解决。。。
    imxz
        6
    imxz  
    OP
       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
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4772 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 04:05 · PVG 12:05 · LAX 21:05 · JFK 00:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.