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

MySQL Order by DESC if column = X, otherwise ASC

如果 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

这是一种方法:

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 

您不能从 CASE 表达式中 return DESCASC。使用 UNIX_TIMESTAMP,日期字段 start_date 被转换为一个整数,可用于按降序存储(一旦取反)。

Demo here