使用 IN 语句时,如何按数组中 id 的顺序对得到的结果进行排序:
SELECT id,name from table WHERE id IN (23, 33, 55, 2)
我想得到:
+----+---------+
| id | name |
+----+---------+
| 23 | name1 |
| 33 | name2 |
| 55 | name3 |
| 2 | name4 |
+----+---------+
按此顺序
只需在查询末尾添加:
order by field(id, 23, 33, 55, 2)
您可以尝试使用 JOIN。不能保证按此顺序返回,但对于 MySQL,这在大多数情况下都是正确的:
SELECT table.id, table.name
FROM (
SELECT 23 id UNION SELECT 33 id UNION SELECT 55 id UNION SELECT 2
) a
JOIN table
ON a.id = table.id
您的订单是如何确定的?如果您可以提供排序功能,它就会变得容易。
SELECT id,name from table WHERE id IN (23, 33, 55, 2) ORDER BY FIELD (id, 2, 23, 33, 55)
你可以尝试这样的事情:
SELECT t.id,t.name
from
(select 23 as id,1 as rnk union all
select 33 as id,2 union all
select 55 as id,3 union all
select 2 as id,4 )input
join table t
on t.id=input.id
order by input.rnk
SELECT id,name from table WHERE id IN (23, 33, 55, 2) ORDER BY id = 23 DESC, id = 33 DESC, id = 55 DESC, id = 2 DESC
不是特定于数据库的解决方案,但仍然有效