在 MySQL“IN"中维护秩序询问 [英] Maintaining order in MySQL "IN" query

查看:22
本文介绍了在 MySQL“IN"中维护秩序询问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表

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.

这篇关于在 MySQL“IN"中维护秩序询问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆