STEELHE4RT
STEELHE4RT

Reputation: 215

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. On my website however, no results are found.

I tried replacing spaces in the keyword with %s, but that didn't change anything.

Upvotes: 2

Views: 6041

Answers (2)

Oskar Persson
Oskar Persson

Reputation: 6743

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

I then tried it by first exploding the search string by whitespaces, and then imploding the result with %' OR tags.tag LIKE '%. This took about 0,06 seconds with the same amount of products and tags.

Upvotes: 0

Till Helge
Till Helge

Reputation: 9311

The problem is that LIKE does pattern matching rather than actually search for keywords. You should create a fulltext Index on your database columns and use WHERE MATCH keywords AGAINST column. That will properly search for all keywords in any order and be a lot faster anyway.

Upvotes: 1

Related Questions