本文介绍了在 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"中维护秩序询问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
The End


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)