在MySQL"IN"中保持顺序.询问 [英] Maintaining order in MySQL "IN" query

查看:71
本文介绍了在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天全站免登陆