MySQL 關鍵字模糊匹配,並按照匹配度排序

MySQL 關鍵字模糊匹配,並按照匹配度排序。sql

方式1、按照關鍵字搜索,而後根據關鍵字所佔比例排序優化

SELECT
	drug_name,
	pinyin
FROM
	tbl_drug
WHERE
	pinyin LIKE '%AM%'
ORDER BY
	LENGTH(pinyin);

效果以下code

方式2、將關鍵字開頭記錄排序在前blog

SELECT
	drug_name,
	pinyin
FROM
	tbl_drug
WHERE
	pinyin LIKE 'AM%'
UNION
	SELECT
		drug_name,
		pinyin
	FROM
		tbl_drug
	WHERE
		pinyin LIKE '%AM%';

效果以下排序

方式3、將關鍵字開頭排序在前,再根據匹配度排序記錄string

SELECT
	drug_name,
	pinyin
FROM
	(SELECT
		drug_name,
		pinyin
	FROM
		tbl_drug
	WHERE
		pinyin LIKE 'AM%'
	ORDER BY
		LENGTH(pinyin)
	LIMIT 999999) t1
UNION
	SELECT
		drug_name,
		pinyin
	FROM
		(SELECT
			drug_name,
			pinyin
		FROM
			tbl_drug
		WHERE
			pinyin LIKE '%AM%'
		ORDER BY
			LENGTH(pinyin)
		LIMIT 999999) t2
LIMIT 0,20;

結果以下,這塊中文「()」所佔長度較大。在此有一個問題,子查詢的排序無效,若是子查詢中order by 不帶limit,會被優化器幹掉it

以上方式爲網上整理總結,下面這個方式爲我的改進class

方式4、先根據關鍵字所在字段index排序,而後再根據匹配度排序搜索

SELECT
    drug_name,
    pinyin
FROM
    tbl_drug
WHERE
    pinyin LIKE '%AM%'
ORDER BY
    LENGTH(substring_index(pinyin,'AM',1)),
    LENGTH(pinyin)
LIMIT 0,20

效果以下im

延伸版:

SELECT
	drug_name,
	pinyin 
FROM
	tbl_drug 
WHERE
	drug_name LIKE '%阿%' 
	OR pinyin LIKE '%阿%' 
ORDER BY
	LOCATE( "阿", pinyin ),
	LOCATE( "阿", drug_name ),
	LENGTH( pinyin );

結果以下:

相關文章
相關標籤/搜索