在 MySQL“IN"中维护秩序询问

2021-11-20 00:00:00 sql mysql

我有下表

DROP TABLE IF EXISTS `test`.`foo`;
CREATE TABLE  `test`.`foo` (
  `id` int(10) unsigned NOT NULL auto_increment,
  `name` varchar(45) NOT NULL,
  PRIMARY KEY  (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

然后我尝试根据主键获取记录

Then I try to get records based on the primary key

SELECT * FROM foo f where f.id IN (2, 3, 1);

然后我得到以下结果

+----+--------+
| id | name   |
+----+--------+
|  1 | first  |
|  2 | second |
|  3 | third  |
+----+--------+
3 rows in set (0.00 sec)

可以看出,结果是按 id 排序的.我想要实现的是按照我在查询中提供的顺序获得排序的结果.鉴于这个例子,它应该返回

As one can see, the result is ordered by id. What I'm trying to achieve is to get the results ordered in the sequence I'm providing in the query. Given this example it should return

+----+--------+
| id | name   |
+----+--------+
|  2 | second |
|  3 | third  |
|  1 | first  |
+----+--------+
3 rows in set (0.00 sec)

推荐答案

正如另一个答案所提到的:您发布的查询没有关于您希望结果的顺序,只是您希望获得的结果.

As the other answer mentions: the query you posted has nothing about what order you'd like your results, just which results you'd like to get.

要对结果进行排序,我将使用 ORDER BY FIELD():

To order your results, I would use ORDER BY FIELD():

SELECT * FROM foo f where f.id IN (2, 3, 1)
ORDER BY FIELD(f.id, 2, 3, 1);

FIELD 的参数列表可以是可变长度的.

The argument list to FIELD can be variable length.

相关文章