Home > Database > Mysql Tutorial > body text

Mysql数据库like模糊查询中文字段不准确的临时解决办法

WBOY
Release: 2016-06-07 15:34:46
Original
1713 people have browsed it

在mysql下,在进行like检索时,有时候会返回一些与查询词不相关的记录,如查找 %s% 时,返回的结果中可能有中文字符,却没有s字符存在,这与数据库中文编码规则有关 如希望查找title中含有字母s的所有新闻: select * from test.news where title like ' % s

在mysql下,在进行like检索时,有时候会返回一些与查询词不相关的记录,如查找 “%s%” 时,返回的结果中可能有中文字符,却没有s字符存在,这与数据库中文编码规则有关

如希望查找title中含有字母s的所有新闻:  

<span>select</span> <span>*</span> <span>from</span> test.news <span>where</span> title <span>like</span> <span>'<span>%</span>s<span>%</span>'</span>
Copy after login

返回的结果中有一些包含s,而有些则只有中文,很郁闷(也很邪恶,嘿嘿)。

测试了下,发现一种解决方法,就是使用 BINARY(是CAST(<em><code>str AS BINARY)简短写法) 强制转换进行检索

<span>select</span> <span>*</span> <span>from</span> test.news <span>where</span> <span>binary</span> title <span>like</span> <span>'<span>%</span>s<span>%</span>'</span>
Copy after login

这样结果就比较准确了,但还有一个问题,就是字母区分大小写,检索的时候依然不正确,只好再转化一下了:

<span>select</span> <span>*</span> <span>from</span> test.news <span>where</span> <span>binary</span> <span>ucase</span><span>(</span>title<span>)</span> <span>like</span>  <span>'<span>%</span>s<span>%</span>'</span>
Copy after login

如此,临时解决办法搞定,不过速度会变慢,希望以后的mysql版本能解决掉此问题。

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template