imxz
V2EX  ›  问与答

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

  •  
  •   imxz · Jul 16, 2014 · 3211 views
    This topic created in 4325 days ago, the information mentioned may be changed or developed.
    数据表中有一个字段为 start_time,储存的是Unix时间戳,值包括过去时间和未来时间,要实现的排序原则如下:
    1、过去的时间按照时间戳递减排序
    2、未来的时间按照未来时间戳减去现在时间戳的值递增排序

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

    排序前:
    1405495901 1405495902 1405495904 1405495905

    排序后:
    1405495904 1405495905 1405495902 1405495901
    6 replies    2014-07-17 13:50:50 +08:00
    hellojinjie
        1
    hellojinjie  
       Jul 16, 2014
    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  
       Jul 16, 2014
    首先这个用SQL去操作很蛋疼,程序上用两条SQL语句不就搞定?
    其次设计上本身就不合理,过去时间跟未来时间怎么能混在一起呢?
    lu18887
        3
    lu18887  
       Jul 16, 2014
    @hellojinjie union正解
    imxz
        4
    imxz  
    OP
       Jul 16, 2014
    @hellojinjie 谢谢你
    imxz
        5
    imxz  
    OP
       Jul 17, 2014
    @hellojinjie 测试了一下,然后发现 order by子句必须写在最后一个结果集里,并且其排序规则将改变操作后的排序结果。 所以问题还是没有解决。。。
    imxz
        6
    imxz  
    OP
       Jul 17, 2014
    这样子就行了:

    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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   986 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 701ms · UTC 19:45 · PVG 03:45 · LAX 12:45 · JFK 15:45
    ♥ Do have faith in what you're doing.