简体   繁体   中英

Order by in mysql without asc and desc

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;

您可以使用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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM