How to define a custom ORDER BY order in mySQL

后端 未结 4 2040
孤街浪徒
孤街浪徒 2020-11-22 12:53

In MySQL how do I define a custom sorting order.

To try to explain what I want consider this table:

ID  Language    Text
0   ENU         a
0   JPN           


        
4条回答
  •  日久生厌
    2020-11-22 13:41

    If those are the only three values, then you can use a CASE expression:

    ORDER BY `ID`,
             CASE `Language`
             WHEN 'ENU' THEN 1
             WHEN 'JPN' THEN 2
             WHEN 'DAN' THEN 3
             END
    

    (If there could be other values, then you may want to add some extra logic to keep the ordering consistent; for example, you might add ELSE 4 to that CASE expression, and then order by Language itself as the third ordering criterion:

    ORDER BY `ID`,
             CASE `Language`
             WHEN 'ENU' THEN 1
             WHEN 'JPN' THEN 2
             WHEN 'DAN' THEN 3
             ELSE 4
             END,
             `Language`
    

    )

提交回复
热议问题