开发者

SQL Sort Order by The Order Specified In the Query

开发者 https://www.devze.com 2023-01-10 14:37 出处:网络
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 the IDs will change from q

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 the IDs will change from query to query and there is no pattern to the order.

I know it's possible to alter the data model, create temp tables, etc. But trust me that those types of solutions will not work in my situation. I also am unable to alter the order of the result objects in my application code.

I'm also aware that different database engines sort things differently, there are no guarantees in some situations blah blah blah. I just want to no, is this possible?

I'll be 开发者_运维问答using mysql or sql server if that helps :)


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


Select ..
From Clauses
Where Id In(0,2,5,1,3)
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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号