In MySQL, I have SQL like
select id from user where id IN (2, 3, 1);
But MySQL return the row as 1, 2, 3, is it possible t开发者_开发百科o force MySQL to return the order same as my original order 2, 3, 1?
Thanks.
You can use the FIELD
function:
select id from user where id IN (2, 3, 1) ORDER BY FIELD(id, 2, 3, 1);
For portable code, use CASE/WHEN
. It is supported by all (major) dbms.
order
by case when id = 2 then 1
when id = 3 then 2
when id = 1 then 3
end
you can also order by LOCATE like this:
SELECT
`id`
FROM
`user`
WHERE
`id` IN(2, 3, 1)
ORDER BY
LOCATE(`id`, "2 3 1")
Felix
精彩评论