You can use FIELD() function
SELECT
*
FROM
book_history
ORDER BY FIELD(`status`, 1, 0, 2)
题
I have a table 'book_history' with a field 'status'
So there are three values for the field 'status' => 0,1,2
Now i want to query it in orderby - I know order by asc and order by desc is there. But how i really want is
select * from book_history order by status 1,0,2
I checked with order by then also. But I was not able to make my query.
So the final output will be - first it should list the status=1, then status=0 and then status='2'
Any help.
Thanks,
Kimz
解决方案
You can use FIELD() function
SELECT
*
FROM
book_history
ORDER BY FIELD(`status`, 1, 0, 2)
其他提示
Use below query to force order in query:
select * from book_history
ORDER BY FIELD (status,1,0,2);
For more information if there is more values and you keep your values on top and rest values after that then you can use below query:
select * from book_history
ORDER BY FIELD (status,2,0,1) desc;
You can use ORDER BY FIELD:
SELECT * FROM book_history ORDER BY FIELD(status, 1,0,2)
Use a case expression to get an order key:
select *
from book_history
order by
case status
when 1 then 100 -- any small value would do here
when 0 then 200 -- any medium value would do here
when 2 then 300 -- any big value would do here
end;
Another alternative with UNION
:
select * from book_history where status = 1
UNION
select * from book_history where status = 0
UNION
select * from book_history where status = 2