mysql - MySql 用like 选择并根据找到的子字符串的数量给出权重
问题描述
我有一张桌子(书)
id, title
我使用 REGEXP 匹配进行了选择
select title
from books
where title REGEXP "word1|word2|...|wordn"
为了获得这样的查询,我怎样才能在标题中找到多少个单词?
select title, numberofwordsfound
from books
where title REGEXP "word1|word2|...|wordn"
在此先感谢大家:)
解决方案
一种选择使用派生表列出单词,然后进行聚合:
select b.id, b.title, count(*) no_matches
from books b
inner join (
select 'word1' word
union all select 'word2'
union all select 'word3'
) w on b.title like concat('%', w.word, '%')
group by b.id, b.title
order by no_matches desc
在 MySQL 的最新版本中,您可以使用VALUES()
row-constructor 枚举单词,从而缩短查询:
select b.id, b.title, count(*) no_matches
from books b
inner join (values(row('word1'), row('word2'), row('word3')) b(word)
on b.title like concat('%', w.word, '%')
group by b.id, b.title
order by no_matches desc
这假设“单词”就是那个 - 单词。如果它们包含正则表达式模式,则您需要使用正则表达式匹配而不是like
:
on b.title regexp w.word
推荐阅读
- haskell - 当“修改”具有相同值的字段时,无法将类型“HandlerSite m0”与“HandlerSite m”匹配
- python - 如何将编辑的txt文件保存到新的txt文件中?
- java - 在这种情况下仅调整图像(png)的大小时,BitmapFactory 真的有必要吗?
- python - 如何获取所有可能响应模式的容器名称?
- ios - Facebook登录按钮不会立即更改为注销按钮在swift中登录后立即
- java - 如何在 Java 运行时生成现有类的字节码?
- github - 如果您将合作者添加到 github 公共存储库,他们会删除或损坏任何东西吗?
- asp.net - Web 应用程序在 Visual Studio 2017 中自动更改为网站
- git - 如何将 Github 中的整个 Projects Docs 下载为 Pdf?
- tabulator - 如何为呈现的页码设置持久性?