mysql使用like进行选择,并根据找到的子字符串数给出权重

omhiaaxx  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(263)

我有一张table(书)

id, title

我选择了与regexp匹配的

select title 
from books 
where title REGEXP "word1|word2|...|wordn"

我怎样才能在标题中找到多少单词来获得这样的查询呢?

select title, numberofwordsfound 
from books 
where title REGEXP "word1|word2|...|wordn"

提前感谢大家:)

l7mqbcuq

l7mqbcuq1#

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

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() 行构造函数来枚举单词,从而缩短查询:

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
plupiseo

plupiseo2#

你可以用一个技巧 regexp_replace() 和捕获组:

select title,
       length(regexp_replace(title, '(word1|word2|...|wordn)', '$1x')) - length(title) as num_matches
from books 
where title REGEXP 'word1|word2|...|wordn';

这是一把小提琴。

相关问题