首页 > 解决方案 > 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"

在此先感谢大家:)

标签: mysqlsqlstringsql-likeregexp-like

解决方案


一种选择使用派生表列出单词,然后进行聚合:

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

推荐阅读