简体   繁体   中英

How to sort with specific order in mysql query?

I have following sample table and one status field.

Name | status
-------------
Ab   | 2
Xy   | 0
Pq   | 3
Rs   | 1

I would like to execute query and would like to sort in this way.

Name | status
-------------
Rs   | 1
Ab   | 2
Pq   | 3
Xy   | 0

Is it possible in MySql query?

Note : Here status field is ENUM .

You can sort by the status but put 0 at the end by the first order condition.

In MySQL you can do (since boolean results are evaluated to 1 and 0 )

select * from your_table
order by status = 0,
         status

in other DB engines you can use

select * from your_table
order by case when status <> 0 then 1 else 2 end,
         status

你也可以尝试

order by find_in_set(`status`, '1,2,3,0');

I got Four solutions for this:-

SELECT * FROM b ORDER BY FIELD(status,3,0);

SELECT * FROM b ORDER BY find_in_set( status , '1,2,3,0');

SELECT * FROM b ORDER BY status = 0,status;

SELECT * FROM b ORDER BY CASE WHEN status <> 0 THEN 1 ELSE 2 END, status;

Here is the MySQL query to sort the data in ASC or DESC order

  SELECT column_name(s)
  FROM table_name
  ORDER BY column_name(s) ASC|DESC

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