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.

If str is NULL, the return value is 0 because NULL fails equality comparison with any value. FIELD() is the complement of ELT().

 

与FIND_IN_SET大体相似,就是如str存在于str1,str2,str3,...列中,则返回str的位置值。如不存在则返回0。如果FIELD中参数均为字符/数值类型,则进行字符/数值比较。否则作为双精浮动数值比较。如str为空则返回0。该函数是作为ELT()函数的一个补充

 

可以进行如下应用:
select * from table where id IN (3,6,9,1,2,5,8,7) order by field(id,3,6,9,1,2,5,8,7);

排序过程:把选出的记录的 id 在 FIELD 列表中进行查找,并返回位置,以位置作为排序依据。
这样的用法,会导致 Using filesort,是效率很低的排序方式。除非数据变化频率很低,或者有长时间的缓存,否则不建议用这样的方式排序。