简体   繁体   English

使用LIKE的带空格的MySQL搜索字符串

[英]MySQL Search String with Spaces Using LIKE

I'm building a search on my site and I noticed it doesn't work when you enter more than one word into the search. 我正在我的网站上进行搜索,但是当您在搜索中输入多个单词时,我发现它不起作用。 Here's the gist of the query: 这是查询的要点:

SELECT * FROM `blog` WHERE `content` LIKE '%$keyword%' OR `title` LIKE '%$keyword%' ORDER BY `id` DESC

The weird things is that when I test the query in phpMyAdmin it returns the expected results. 奇怪的是,当我在phpMyAdmin中测试查询时,它将返回预期的结果。 On my website however, no results are found. 但是,在我的网站上找不到任何结果。

I tried replacing spaces in the keyword with %s, but that didn't change anything. 我尝试用%s替换关键字中的空格,但这没有任何改变。

The problem is that LIKE does pattern matching rather than actually search for keywords. 问题是LIKE会进行模式匹配,而不是实际搜索关键字。 You should create a fulltext Index on your database columns and use WHERE MATCH keywords AGAINST column . 您应该在数据库列上创建全文索引,并使用WHERE MATCH keywords AGAINST column That will properly search for all keywords in any order and be a lot faster anyway. 这样可以正确地以任何顺序搜索所有关键字,并且无论如何都要快得多。

I just tried this in my database and using LIKE in the query is more than 66 times as fast than using MATCH with fulltext index. 我只是在数据库中尝试过,在查询中使用LIKE的速度是使用带有全文索引的MATCH速度的66倍以上。 I'm using two tables which are "connected" to each other. 我正在使用两个相互“连接”的表。 One is tags and the other one is products. 一种是标签,另一种是产品。

So what I did was that I added a fulltext index to the tag column in the tags table and performed the match against that column. 所以我要做的是,我向标签表中的标签列添加了全文索引,并对该列进行了匹配。 The query than joins the products and then spits out some data about the item. 查询然后加入产品,然后吐出有关该物品的一些数据。 That took about 4 seconds with ~3000 products & ~3000 tags. 大约3000个产品和大约3000个标签花费了大约4秒钟的时间。

I then tried it by first exploding the search string by whitespaces, and then imploding the result with %' OR tags.tag LIKE '% . 然后,我首先通过用空格将搜索字符串%' OR tags.tag LIKE '% ,然后将结果与%' OR tags.tag LIKE '% This took about 0,06 seconds with the same amount of products and tags. 在使用相同数量的产品和标签的情况下,这大约需要0.06秒。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM