MySQL - 如何使用 LIKE 搜索精确的单词匹配?

2021-11-20 00:00:00 sql-like select mysql

我正在使用此查询来选择数据:

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.

例如,我想选择产品BLA",但我的查询也选择产品BLABLA".明确地说,如果我想选择产品 1",我不希望查询选择产品 11".

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

有人知道如何管理吗?

谢谢.

推荐答案

您只想搜索单词边界吗?如果是这样,一个粗略的版本可能是:

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

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

或者你可以更聪明一点,用下面的REGEXP

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

SELECT * FROM products WHERE product_name RLIKE "[[:<:]]foo[[:>:]]";

相关文章