天天看點

mysql使用in查詢,按照期望的順序輸出結果 MySQL FIELD() function

mysql使用in查詢,按照期望的順序輸出結果,可以使用field函數

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

結果:

mysql使用in查詢,按照期望的順序輸出結果 MySQL FIELD() function

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.