我有一张桌子(书)
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()
行构造函数枚举单词,从而缩短查询时间:
select b.id,count(*) no_matches
from books b
inner join (values(row('word1'),row('word2'),row('word3')) b(word)
on b.title like concat('%',b.title
order by no_matches desc
这假设“单词”就是-单词。如果它们包含正则表达式模式,则需要使用正则表达式匹配而不是like
:
on b.title regexp w.word
,
您可以对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';
Here是db 小提琴。