在 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(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/