MySQL按逗号分隔列表排序

时间:2016-11-03 22:30:48

标签: mysql

我有以下MySQL查询

SELECT * FROM Characters WHERE CharacterID IN (30, 29, 1, 292, 51)

返回我的字符列表,如下所示

|   CharacterID   |   CharacterName  |
--------------------------------------
|        1        |    Character 1   | 
|       29        |    Character 29  | 
|       30        |    Character 30  | 
|       51        |    Character 51  | 
|      292        |    Character 292 | 

我需要它以与原始逗号分隔值相同的顺序返回。所以在这个特定的例子中,我需要它返回......

|   CharacterID   |   CharacterName  |
--------------------------------------
|       30        |    Character 30  | 
|       29        |    Character 29  | 
|        1        |    Character 1   | 
|      292        |    Character 292 | 
|       51        |    Character 51  | 

无论如何,我可以特别说出像

这样的内容
SELECT * FROM Characters WHERE CharacterID IN (30, 29, 1, 292, 51)
ORDER BY (CharacterID, specifically in the order of (30, 29, 1, 292, 51))

1 个答案:

答案 0 :(得分:3)

您可以按FIELD()

使用订单
SELECT * FROM Characters WHERE CharacterID IN (30, 29, 1, 292, 51)
ORDER BY FIELD(CharacterID, 30, 29, 1, 292, 51)

FIELD()是一个返回逗号分隔列表

的索引位置的函数