MySQL - ORDER BY values within IN()

前端 未结 6 1876
时光说笑
时光说笑 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:39

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

    The FIELD function returns the position of the first string in the remaining list of strings.

    However, it is much better performance-wise to have an indexed column that represents your sort order, and then sort by this column.

提交回复
热议问题