MySQL - How to search for exact word match using L

2019-01-07 20:43发布

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.

10条回答
ゆ 、 Hurt°
2楼-- · 2019-01-07 21:17

try to use regular expression in query

mysql_query("SELECT * FROM products WHERE product_name regexp '".$search."'");
查看更多
倾城 Initia
3楼-- · 2019-01-07 21:18

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.

查看更多
三岁会撩人
4楼-- · 2019-01-07 21:21

Use equals (=)?

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

If you are looking to match EXACT words don't use LIKE.

EDIT: That clears things up a bit then. Just add a space after the search term. Or even add the hyphen (-) if that is always in the search term.

mysql_query("SELECT * FROM products WHERE product_name LIKE '".$search." -%'"); 
查看更多
疯言疯语
5楼-- · 2019-01-07 21:25

To exact match you should use:

mysql_query("SELECT * FROM products WHERE product_name = '" . $search . "'");
查看更多
登录 后发表回答