开发者

MySQL WHERE IN - Ordering

开发者 https://www.devze.com 2022-12-26 13:42 出处:网络
W开发者_运维问答hen using: SELECT * FROM some_table WHERE id IN(4,2,1,3,5); The resulting order is:

W开发者_运维问答hen using:

SELECT * FROM some_table WHERE id IN(4,2,1,3,5);

The resulting order is:

1,2,3,4,5

What can I do to return the results in the same order I queried them in?

thanks


SELECT *
FROM some_table
WHERE id IN(4,2,1,3,5)
ORDER BY FIELD (id, 4,2,1,3,5);

More info on MySQL FIELD() function


SELECT *
FROM some_table 
WHERE id IN (4,2,1,3,5)
order by case id
    when 4 then 1
    when 2 then 2
    when 1 then 3
    when 3 then 4
    when 5 then 5
end 

or

SELECT * FROM some_table WHERE id = 4
union all
SELECT * FROM some_table WHERE id = 2
union all
SELECT * FROM some_table WHERE id = 1
union all
SELECT * FROM some_table WHERE id = 3
union all
SELECT * FROM some_table WHERE id = 5
0

精彩评论

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

关注公众号