How to define a custom ORDER BY order in mySQL

后端 未结 4 2054
孤街浪徒
孤街浪徒 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:30

    You have a couple of options offhand, the first is to change Language to be ENUM (assuming this is possible, and you only expect a few variations)

    If you specify it as ENUM('ENU','JPN','DAN') then ORDER Language ASC will order in the order you specify.

    The second will involve a case somewhere, i.e.

    SELECT * FROM table
    ORDER BY CASE Language
        WHEN 'ENU' THEN 3
        WHEN 'JPN' THEN 2
        WHEN 'DAN' THEN 1
        ELSE 0
    END DESC, ID ASC
    

    Performance-wise the ENUM method will return faster results, but be more hassle if you need to add more languages. A third option would be to add a normalisation table for the Languages however that may be overkill in this instance.

提交回复
热议问题