我正在尝试从句子(字符串)中获取精确的单词(子字符串)匹配,该句子(字符串)至少包含一个精确的单词匹配(如果不是文章或动名词则最好)存储在数据库中句子中的任何位置,如下所示:
SELECT q
FROM q
WHERE q LIKE '%$q%' OR '$q' LIKE CONCAT('%', q, '%')
ORDER BY CASE WHEN q = '$q' THEN 0
WHEN q LIKE '$q%' THEN 1
WHEN q LIKE '%$q%' THEN 2
WHEN q LIKE '%$q' THEN 3
ELSE 4
END, q ASC
LIMIT 10;
但它返回以下值为 $q = "best seo company for small business";
的查询结果:
best seo company for small business
best seo
best seo company
mpa
seo
seo com
seo company
small
small b
small bu
期望的输出:
best seo company for small business
best seo
best seo company
seo
seo company
small
不需要的输出:
mpa
seo com
small b
small bu
如何排除不需要的输出?
注意:以下问题:
Search for "whole word match" in MySQL
Make MySQL LIKE Return Full Word matches Only
MySQL Finding Substring Matches and Group by Match Full Word
建议一些与我正在寻找的解决方案无关的答案。
最佳答案
这个问题的解决方案可以是 REGEXP q+
它匹配任何包含至少一个 q 的字符串
。
虽然它将匹配 seo company
与:
affordable seo company
atlanta seo company
austin seo company
automotive seo company
best atlanta seo company
best local seo company
best los angeles seo company
best organic seo company
best real estate seo company
best seo company
best seo company for google
best seo company for lawyers
best seo company for small business
best seo company in india
best seo company in the usa
best seo company in the world
best seo company india
best seo company los angeles
best seo company miami
boise seo company
boston seo company
california seo company
charleston seo company
charlotte seo company
cheap seo company
它不能将 best seo company for small business
与除自身以外的任何上述条款相匹配。
试试这个:
SELECT q
FROM q
WHERE q REGEXP '$q+'
ORDER BY CASE WHEN q = '$q' THEN 0
WHEN q LIKE '$q%' THEN 1
WHEN q LIKE '%$q%' THEN 2
WHEN q LIKE '%$q' THEN 3
ELSE 4
END, q ASC
LIMIT 10
关于MySQL通过相关性从句子的任何位置获取完整的单词匹配(不是字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49169017/