MySQL如果列= X则由DESC排序,否则为ASC

时间:2016-02-17 19:07:46

标签: mysql sql-order-by

如果finished = 1,如何通过start_date DESC命令查询,否则命令start_date ASC。现在它看起来像这样:

SELECT game_id, 
    event_id, 
    start_date, 
    best_of, 
    home_team_id, 
    away_team_id, 
    home_value, 
    away_value, 
    home_result, 
    away_result, 
    stream_url, 
    stats_url, 
    comments, 
    finished 
FROM betting_games 
ORDER BY finished ASC, 
    start_date ASC 
LIMIT 5

1 个答案:

答案 0 :(得分:3)

以这种方式:

SELECT *
FROM betting_games
ORDER BY finished ASC, 
         CASE 
            WHEN finished =  1 THEN - 1 * UNIX_TIMESTAMP(start_date)
            ELSE UNIX_TIMESTAMP(start_date)
         END ASC 

您无法从DESC表达式返回ASCCASE。使用UNIX_TIMESTAMP,日期字段start_date将转换为整数,可用于按降序存储(一旦否定)。

Demo here