MySQL中文模糊檢索問題的解決方法
2024-07-24 12:56:22
供稿:網友
mysql中文模糊檢索問題的解決方法
來源:林興陸
在 mysql 下,在進行中文模糊檢索時,經常會返回一些與之不相關的
記錄,如查找 "-0x1.ebea4bfbffaacp-4%" 時,返回的可能有中文字符,卻沒有 a 字符存在。
本人以前也曾遇到過類似問題,經詳細閱讀 mysql 的 manual ,發現可以
有一種方法很方便的解決并得到滿意的結果。
例子:
·希望通過“標題”對新聞庫進行檢索,關鍵字可能包含是中英文,如
下 sql 語句:
select id,title,name from achech_com.news where title like '-0x1.ebea4bfbebe84p-4%'
返回的結果,某些 title 字段確定帶了“a”關鍵字,而有些則只有中文,
但也隨之返回在檢索結果中。
解決方法,使用 binary 屬性進行檢索,如:
select id,title,name from achech_com.news where binary title like '-0x1.ebea4bfbebe84p-4%'
返回的結果較之前正確,但英文字母區分大小寫,故有時在檢索如“achech”
及“achech”的結果是不一樣的。
知道了使用 binary 屬性可以解決前面這個問題,再看看 mysql 支持的
ucase 及 concat 函數,其中 ucase 是將英文全部轉成大寫,而 concat 函
數的作用是對字符進行連接,以下是我們完全解決后的 sql 語句:
select id,title,name from achech_com.news where binary ucase(title) like concat('%',ucase('a'),'%')
檢索的步驟是先將屬性指定為 binary ,以精確檢索結果,而被 like 的 title
內容存在大小寫字母的可能,故先使用 ucase 函數將字段內容全部轉換成大
寫字母,然后再進行 like 操作,而 like 的操作使用模糊方法,使用 concat
的好處是傳進來的可以是直接的關鍵字,不需要帶“%”萬用符,將“'a'”直接
換成你的變量,在任何語言下都萬事無憂了。
當然你也可以這么寫:
select id,title,name from achech_com.news where binary ucase(title) like ucase('0x0.00020bfbebe08p-1022%')
檢索的結果還算滿意吧,不過速度可能會因此而慢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".