MySQL通过相关性从句子的任何位置获取完整的单词匹配(不是字符)

标签 mysql regex

我正在尝试从句子(字符串)中获取精确的单词(子字符串)匹配,该句子(字符串)至少包含一个精确的单词匹配(如果不是文章或动名词则最好)存储在数据库中句子中的任何位置,如下所示:

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/

相关文章:

php - 如何使用准确的帖子标题进行查询

Python MySQLdb/MySQL INSERT IGNORE 并检查是否被忽略

PHP MYSQL 无法在表中存储对象属性

php - 正则表达式:比较两个字符串以查找头韵和谐音

java - 用于屏蔽字符串开头 8 个字符的正则表达式

MySQL USE 语句没有效果

mysql - Unique 不适用于 Node.js Sails.js "sails-mysql"

c# - 正则表达式按模式查找并仅替换一部分

regex - 匹配 Google 表格中字符串末尾的部分文本

java - SpannableStringBuilder 用 Regex 替换内容