Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - How to search for exact word match using LIKE?

I'm using this query to select data:

mysql_query("SELECT * FROM products WHERE product_name LIKE '%".$search."%'"); 

The only problem is, that it sometimes selects more, than I would like.

For example, I would like to select product "BLA", but my query select product "BLABLA" as well. To be clear, if i wanted to select "Product 1", I don't want the query to select "Product 11".

Does anybody know how to manage that?

Thanks.

like image 831
Mike Avatar asked Apr 21 '11 10:04

Mike


People also ask

How do I use exact string match in SQL?

You should use this query instead for an exact match of the value PC: SELECT * FROM TransDetail TD WHERE TD. ModUserId = 'PC'; When using % in the WHERE clause you are using a wildcard that stands for 0 or more occurrences of characters in that position.

How do I search for a word in MySQL?

MySQL LOCATE() Function The LOCATE() function returns the position of the first occurrence of a substring in a string. If the substring is not found within the original string, this function returns 0.


2 Answers

Do you just want to search on word boundaries? If so a crude version might be:

SELECT * FROM products WHERE product_name LIKE "% foo %"; 

Or you could be a bit cleverer and look for word boundaries with the following REGEXP

SELECT * FROM products WHERE product_name RLIKE "[[:<:]]foo[[:>:]]"; 
like image 185
James C Avatar answered Sep 25 '22 20:09

James C


Found this question on Google, so I figure that some people may still stumble upon this so here's my pretty inelegant attempt:

SELECT * FROM products WHERE product_name LIKE 'BLA %' #First word proceeded by more words OR WHERE product_name LIKE '% BLA' #Last word preceded by other words OR WHERE product_name LIKE '% BLA %' #Word in between other words OR WHERE product_name = 'BLA'; #Just the word itself 

Not sure about the efficiency or if this covers all cases, so feel free to downvote if this is really inefficient or too inelegant.

like image 36
PulpDood Avatar answered Sep 24 '22 20:09

PulpDood