【发布时间】:2010-12-10 13:03:15
【问题描述】:
我有下表
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;
然后我尝试根据主键获取记录
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 排序的。我想要实现的是按照我在查询中提供的顺序排列结果。鉴于此示例,它应该返回
+----+--------+
| id | name |
+----+--------+
| 2 | second |
| 3 | third |
| 1 | first |
+----+--------+
3 rows in set (0.00 sec)
【问题讨论】:
-
在 MySQL 网站上查看这个答案:forums.mysql.com/read.php?97,210905,210918#msg-210918——我认为你会遇到麻烦,期待 in() 表现得像这样。 MySQL 不会真正对结果进行排序,除非您明确告知它,并且您的数据中没有任何内容可以按照您想要的方式对其进行排序。