简体   繁体   中英

How to use “ORDER BY FIELD” to sort the result of a SQL

If there is a data shown as below;

id  cnt_stamp    
1  999 
2  3
3  9
4  3 
5  1000
6  30

If an input is (4, 1, 2, 3) in this order, I would like to get only (3, 999, 3, 9). To achieve this, I created a SQL

SELECT `cnt_stamp`
FROM `stm_events`
ORDER BY FIELD(`id`, 4, 1, 2, 3);

But it returns (1000, 30, 3, 999, 3, 9) instead. How should I fix my SQL to achieve my goal? Thank you for taking your time.

FIELD will assign NULL to any non matching id , and nulls sort first by default in MySQL. If you don't want to see non matching items at all you may just add a WHERE clause:

SELECT cnt_stamp
FROM stm_events
WHERE id IN (1, 2, 3, 4)
ORDER BY FIELD(id, 4, 1, 2, 3);

If you want to see all your data, with non matching id values at the end, then reverse the order of the field list and sort descending:

SELECT cnt_stamp
FROM stm_events
ORDER BY FIELD(id, 3, 2, 1, 4) DESC;

Demo

Use COALESCE function :

SELECT `cnt_stamp` 
  FROM `stm_events` 
 ORDER BY COALESCE(`id`,FIELD(`id`,4,1,2,3));

SQL Fiddle Demo

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