MySQL IN 运算符结果集顺序

标签 mysql sql-order-by

在 MySQL 中,当使用 IN 运算符时,我们可以要求 MySQL 以与 IN 集相同的顺序返回结果集(记录集)吗?

解释: 假设我们有一张 table 项目(item_id,item_name);

和查询:

select * from items where item_id in (1,3,5,7,2,4,6,8);

我们能否拥有结果集(记录集),其中记录的顺序与 IN 运算符集的顺序相同。 即 1,3,5,7,2,4,6,8 of record_id

事实并非如此; MySQL 似乎优化了搜索并给出了默认顺序(与存储在文件系统中的那些记录的顺序相同)。

最佳答案

您可以在 ORDER BY 子句中使用 MySQL 的 field 函数:

select *
from items
where item_id in (1,3,5,7,2,4,6,8)
order by field(item_id, 1,3,5,7,2,4,6,8)

field function :

FIELD(str,str1,str2,str3,...)

Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

If all arguments to FIELD() are strings, all arguments are compared as strings. If all arguments are numbers, they are compared as numbers. Otherwise, the arguments are compared as double.

关于MySQL IN 运算符结果集顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8178530/

相关文章:

mysql - 带文本的 dbSendQuery INSERT 语句

mysql - 使用 SQL 进行多重排序

mysql - 子查询 - 记录不是有序的

php - xmlHTTPRequest POST 不发送数据

mysql - 将关联从一对多更改为多对多

mysql - MySQL可以替换多个字符吗?

php - 从 php 更新 sql 表中的字段

MYSQL 按大小写排序

postgresql - PostgreSQL 中奇怪的 ORDER BY 顺序

Mysql:获取最后记录的最佳实践