mysql中文模糊查询|MySQL中文模糊检索问题的解决方法

更新时间:2013-11-18    来源:mysql教程    手机版     字体:

【www.bbyears.com--mysql教程】

在 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".

本文来源:http://www.bbyears.com/shujuku/2084.html

猜你感兴趣

热门标签

更多>>

本类排行