是否可以按照 'where in' 子句中指定的顺序获取结果集?

Is it possible get result set in the order of how it was specified in 'where in' clause?

假设有一个 table employee.

mysql> select * from employee limit 3\G
*************************** 1. row ***************************
     id: 1
   name: consequatur
  phone: 245.939.07
address: 37613 Stiedemann Vista Suite 077
Port Imeldaside, WI 19791
*************************** 2. row ***************************
     id: 2
   name: placeat
  phone: (193)912-8
address: 9742 Feest Mill Suite 275
North Jo, MA 04371-5138
*************************** 3. row ***************************
     id: 3
   name: non
  phone: 1-598-109-
address: 72476 Haley Crest Apt. 698
Isabelberg, SD 20263-9817

假设它包含大量数据。我有 id 想要获取数据。所以我查询并得到以下结果集。

mysql> select e.id, e.name, e.phone from employee e where id in (54,2,16);
+----+-------------+------------+
| id | name        | phone      |
+----+-------------+------------+
|  2 | placeat     | (193)912-8 |
| 16 | consequatur | 245.939.07 |
| 54 | eum         | 629.885.95 |
+----+-------------+------------+
3 rows in set (0.00 sec)

是否可以按照 id 出现的 where id in 子句的顺序获取结果集?所以我期望的是:

+----+-------------+------------+
| id | name        | phone      |
+----+-------------+------------+
| 54 | eum         | 629.885.95 |
|  2 | placeat     | (193)912-8 |
| 16 | consequatur | 245.939.07 |
+----+-------------+------------+
3 rows in set (0.00 sec)

有一个排序标准,returns 顺序为 54、2、16,但假设用例并不要求它始终为 运行。我们一旦了解订单,就不太可能改变。并假设 phone 未编入索引。

此外,请说明与每次查询 运行 时必须执行 table 扫描和文件排序相比,此方法的性能。

没有,但你可以事后排序。

在你的情况下,你可以简单地使用:

order by id desc

更通用的解决方案使用 field():

select e.id, e.name, e.phone
from employee e
where id in (54, 23, 1)
order by field(id, 54, 23, 1);

join:

select e.id, e.name, e.phone
from employee e join
     (select 54 as id, 1 as ord union all
      select 23 as id, 2 as ord union all
      select 1 as id, 3 as ord
     ) i
     on e.id = i.id
order by i.ord;