在 MySQL 下,在進(jìn)行中文模糊檢索時(shí),經(jīng)常會(huì)返回一些與之不相關(guān)的
記錄,如查找 "%a%" 時(shí),返回的可能有中文字符,卻沒(méi)有 a 字符存在。
本人以前也曾遇到過(guò)類(lèi)似問(wèn)題,經(jīng)詳細(xì)閱讀 MySQL 的 Manual ,發(fā)現(xiàn)可以
有一種方法很方便的解決并得到滿(mǎn)意的結(jié)果。
例子:
·希望通過(guò)“標(biāo)題”對(duì)新聞庫(kù)進(jìn)行檢索,關(guān)鍵字可能包含是中英文,如
下 SQL 語(yǔ)句:
select id,title,name from achech_com.news where title like '%a%'
返回的結(jié)果,某些 title 字段確定帶了“a”關(guān)鍵字,而有些則只有中文,
但也隨之返回在檢索結(jié)果中。
解決方法,使用 BINARY 屬性進(jìn)行檢索,如:
select id,title,name from achech_com.news where binary title like '%a%'
返回的結(jié)果較之前正確,但英文字母區(qū)分大小寫(xiě),故有時(shí)在檢索如“Achech”
及“achech”的結(jié)果是不一樣的。
知道了使用 BINARY 屬性可以解決前面這個(gè)問(wèn)題,再看看 MySQL 支持的
UCASE 及 CONCAT 函數(shù),其中 UCASE 是將英文全部轉(zhuǎn)成大寫(xiě),而 CONCAT 函
數(shù)的作用是對(duì)字符進(jìn)行連接,以下是我們完全解決后的 SQL 語(yǔ)句:
select id,title,name from achech_com.news where binary ucase(title) like concat('%',ucase('a'),'%')
檢索的步驟是先將屬性指定為 BINARY ,以精確檢索結(jié)果,而被 like 的 title
內(nèi)容存在大小寫(xiě)字母的可能,故先使用 ucase 函數(shù)將字段內(nèi)容全部轉(zhuǎn)換成大
寫(xiě)字母,然后再進(jìn)行 like 操作,而 like 的操作使用模糊方法,使用 concat
的好處是傳進(jìn)來(lái)的可以是直接的關(guān)鍵字,不需要帶“%”萬(wàn)用符,將“'a'”直接
換成你的變量,在任何語(yǔ)言下都萬(wàn)事無(wú)憂(yōu)了。
當(dāng)然你也可以這么寫(xiě):
select id,title,name from achech_com.news where binary ucase(title) like ucase('%a%')
檢索的結(jié)果還算滿(mǎn)意吧,不過(guò)速度可能會(huì)因此而慢N毫秒喔。
作者:林興陸·Linxinglu@ihw.com.cn
相關(guān)資料:
Relate:
20.16 Case Sensitivity in Searches
By default, MySQL searches are case-insensitive (although there are some character sets that are never case insensitive, such as czech). That means that if you search with col_name LIKE 'a%', you will get all column values that start with A or a. If you want to make this search case-sensitive, use something like INDEX(col_name, "A")=0 to check a PRefix. Or use STRCMP(col_name, "A") = 0 if the column value must be exactly "A".