SQL: select where in 语句返回的list结果是一定和in后面的项的顺序一致吗?

譬如

select * from apple where id in (3, 2, 4)

那么返回的list也是一定根据id 3 2 4这样排序吗?

阅读 6.5k
3 个回答

返回结果的顺序,如果是myisam,跟源数据插入的顺序有关;如果是innodb,跟你具体访问哪个索引有关系,所以要看执行计划。

不是
返回的list结果是这个表里面存储的顺序
举个例子:
建立一个表,结构是这样的:

CREATE TABLE 'aaahello'(
  'id' INT PRIMARY KEY ,
  'name' VARCHAR(20)
);
insert into `aaahello` VALUES (3,'acc');
insert into `aaahello` VALUES (5,'accd');
insert into `aaahello` VALUES (9,'accd');
insert into `aaahello` VALUES (11,'accd');
insert into `aaahello` VALUES (15,'accd');
insert into `aaahello` VALUES (21,'accd');
insert into `aaahello` VALUES (1,'accd');

(注意ID我没有按顺序添加)
然后我再执行一个查询:

select  * from aaahello where id in (21,9,1)

那么他的返回结果是:

+----+------+
| id | name |
+----+------+
| 9  | accd |
| 21 | accd |
| 1  | accd |
+----+------+
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题