MySQL - ORDER BY values within IN()

前端 未结 6 1904
时光说笑
时光说笑 2020-11-27 10:46

I\'m hoping to sort the items returned in the following query by the order they\'re entered into the IN() function.

INPUT:

SELECT id         


        
6条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 11:52

    Another option from here: http://dev.mysql.com/doc/refman/5.0/en/sorting-rows.html

    select * 
    from tablename 
    order by priority='High' DESC, priority='Medium' DESC, priority='Low" DESC;
    

    So in your case (untested) would be

    SELECT id, name
    FROM mytable
    WHERE name IN ('B', 'A', 'D', 'E', 'C')
    ORDER BY name = 'B', name = 'A', name = 'D', name =  'E', name = 'C';
    

    Depending what you're doing I've found it a bit quirky but always got it to work after playing with it a bit.

提交回复
热议问题