SQL Sort Order by The Order Specified In the Query

后端 未结 2 1689
温柔的废话
温柔的废话 2021-01-25 08:14

Say I have a query \"select * from clauses where id in (0,2,5,1,3)\" and I actually want the rows returned in the same order they are specified the where clause. The order of t

2条回答
  •  闹比i
    闹比i (楼主)
    2021-01-25 08:48

    On MySQL, you can use FIND_IN_SET:

    ORDER BY FIND_IN_SET(id, '0,2,5,1,3')
    

    The most portable means of ordering would be to use a CASE expression:

    ORDER BY CASE id
               WHEN 0 THEN 1
               WHEN 2 THEN 2
               WHEN 5 THEN 3
               WHEN 1 THEN 4
               WHEN 3 THEN 5
             END
    

提交回复
热议问题