是否有一种方法可以在SQL中手动指定结果的顺序


Is there a way to specify order of results manually in SQL?

我有一个PHP数组,其中包含要从MySQL数据库中检索的行ID。

$ids = array(35, 20, 1, 5);

有没有什么方法可以构造一个SQL查询,从数据库中检索具有特定ID顺序的行的资源?

换句话说,返回的行列表将首先有ID为35的行,然后是ID为20的行,依此类推

试试这个

<?php
$ids = array(35, 20, 1, 5);
$q = 'select * from table where id in ('.implode(',',$ids).') order by find_in_set(id, '''.implode(',',$ids).''')' ;

在PHP/Javascript端进行排序会更容易,但有一种方法会让人想到如何在SQL:中进行排序

select * from whatever where id in (35,20,1,5) order by
case id when 35 then 0 when 20 then 1 when 1 then 2 when 5 then 3 end