mysql使用in查询,按照期望的顺序输出结果

时间:2022-03-11 15:03:17

mysql使用in查询,按照期望的顺序输出结果,可以使用field函数

SELECT
	ProvinceId,
	ProvinceName
FROM
	btoc_province
WHERE
	ProvinceName IN ('河南', '辽宁', '山西')
ORDER BY
	FIELD(
		provincename,
		'河南',
		'辽宁',
		'山西'
	);

结果:

mysql使用in查询,按照期望的顺序输出结果


MySQL FIELD() function

MySQL FIELD() returns the index position of the searching string from a list of strings. If search string is not found, it returns a 0(zero). If search string is NULL, the return value is 0 because NULL fails equality comparison with any value.

FIELD() is the complement of ELT(). When all arguments of the FIELD() are strings, they are compared as strings. If all arguments are number, they compared as numbers. Other wise all are compared as double.