[英]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). 如果输入按此顺序为(4,1,2,3),我只想得到(3,999,3,9)。 To achieve this, I created a SQL
为此,我创建了一个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. 但是它返回(1000、30、3、999、3、9)。 How should I fix my SQL to achieve my goal?
我应该如何修正SQL以达到目标? Thank you for taking your time.
感谢您抽出宝贵的时间。
FIELD
will assign NULL
to any non matching id
, and nulls sort first by default in MySQL. 在MySQL中,
FIELD
会将NULL
分配给任何不匹配的id
,并且默认情况下,空值首先排序。 If you don't want to see non matching items at all you may just add a WHERE
clause: 如果您根本不想看到不匹配的项目,则可以添加
WHERE
子句:
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: 如果要查看所有数据,但
id
值结尾不匹配,请反转字段列表的顺序并降序排列:
SELECT cnt_stamp
FROM stm_events
ORDER BY FIELD(id, 3, 2, 1, 4) DESC;
Use COALESCE
function : 使用
COALESCE
函数:
SELECT `cnt_stamp`
FROM `stm_events`
ORDER BY COALESCE(`id`,FIELD(`id`,4,1,2,3));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.