mysql SELECT LIKE必须将整个单词仅与变量匹配 [英] mysql SELECT LIKE must match whole words only to the variable
问题描述
我有一个$ string变量,我使用
I have a $string variable, and I use
SELECT * FROM db WHERE description LIKE '%$string%' OR headline LIKE '%$string%'
如图所示,我想搜索描述"和标题"这两个字段,以查看字符串变量是否与它们中的任何一个匹配.
As seen, I want to search the two fields "description" and "headline" to see if the string variable matches any of them.
问题是我希望它与整个单词匹配!
Problem is that I want it to match whole words!!!
例如:如果描述包含"hello",则$ string为'h'就足够了.这不是我想要的,它只需要匹配整个单词!
Ex: If description contains "hello", It is enough if $string is an 'h'. this is not what I want.It has to match the whole word only!
我为此将查询字符串拆分为单词吗?还是什么?
I split the querystring into words for this? or what?
推荐答案
如果您想全字匹配,应该考虑尝试FULLTEXT搜索.一个先决条件是您的表必须使用MyISAM引擎:
If you want full word matching you should consider trying FULLTEXT searching. One prerequisite is that your table must be using the MyISAM engine:
CREATE TABLE test (
id INT(11) UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
headline VARCHAR(120) NOT NULL,
description VARCHAR(255) NOT NULL,
FULLTEXT(headline, description)
) ENGINE=MyISAM;
您将查询匹配项,如下所示:
You would query for matches like so:
SELECT *
FROM test
WHERE MATCH (headline,description) AGAINST('$string');
这还有按相关性对结果进行排序的好处.
This has the added benefit of ordering your results by relevancy.
这篇关于mysql SELECT LIKE必须将整个单词仅与变量匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!