[英]php mysql sort results by order fetched
How can I order the results I get by the order of the ids in the array when using IN statement: 使用IN语句时,如何按数组中ID的顺序对结果进行排序:
SELECT id,name from table WHERE id IN (23, 33, 55, 2)
SELECT ID,表WHERE ID IN中的名称(23,33,55,2)
I want to get: 我想得到:
+----+---------+
| id | name |
+----+---------+
| 23 | name1 |
| 33 | name2 |
| 55 | name3 |
| 2 | name4 |
+----+---------+
in this order 按此顺序
只需在查询末尾添加以下内容:
order by field(id, 23, 33, 55, 2)
You can try to use a JOIN. 您可以尝试使用JOIN。 It is not guaranteed to be returned in this order, but for MySQL this holds true most of the time:
它不能保证按此顺序返回,但是对于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
How is your order determined? 如何确定您的订单? If you can provide a sorting-function it gets easy.
如果您可以提供排序功能,它将变得很容易。
SELECT ID,表中的名称WHERE ID IN(23,33,55,2)ORDER BY FIELD(ID,2,23,33,55)
You could try something like this: 您可以尝试这样的事情:
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
不是数据库特定的解决方案,但仍然有效
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.