MySQL中文模糊檢索問題的解決方案

來源:互聯網
上載者:User
在 MySQL 下,在進行中文模糊檢索時,經常會返回一些與之不相關的
記錄,如尋找 "%a%" 時,返回的可能有中文字元,卻沒有 a 字元存在。
本人以前也曾遇到過類似問題,經詳細閱讀 MySQL 的 Manual ,發現可以
有一種方法很方便的解決並得到滿意的結果。
例子:
·希望通過“標題”對新聞庫進行檢索,關鍵字可能包含是中英文,如
下 SQL 陳述式:
select id,title,name from achech_com.news where title like '%a%'
返回的結果,某些 title 欄位確定帶了“a”關鍵字,而有些則只有中文,
但也隨之返回在檢索結果中。
解決方案,使用 BINARY 屬性進行檢索,如:
select id,title,name from achech_com.news where binary title like '%a%'
返回的結果較之前正確,但英文字母區分大小寫,故有時在檢索如“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('%a%')
檢索的結果還算滿意吧,不過速度可能會因此而慢N毫秒喔。
作者:林興陸·Linxinglu@ihw.com.cn
相關資料:
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".

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.