使用IN语句时,如何按照数组中id的顺序对结果进行排序:
SELECT id,来自表WHERE id IN(23,33,55,2)
的名称
我想得到:
+----+---------+
| id | name |
+----+---------+
| 23 | name1 |
| 33 | name2 |
| 55 | name3 |
| 2 | name4 |
+----+---------+
按此顺序
答案 0 :(得分:6)
只需在查询结尾添加:
order by field(id, 23, 33, 55, 2)
答案 1 :(得分: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
您的订单如何确定?如果你能提供排序功能,那就很容易了。
答案 2 :(得分:2)
SELECT id,表中的名称WHERE id IN(23,33,55,2)ORDER BY FIELD(id,2,23,33,55)
答案 3 :(得分:1)
您可以尝试这样的事情:
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
答案 4 :(得分:1)
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
不是特定于数据库的解决方案,但仍然有效