【问题标题】:MySql select with like and give a weight based on number of substrings foundMySql 用like 选择并根据找到的子字符串的数量给出权重
【发布时间】:2020-08-03 20:25:30
【问题描述】:

我有一张桌子(书)

id, title

我使用 REGEXP 匹配进行了选择

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

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

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

提前感谢大家:)

【问题讨论】:

    标签: mysql sql string sql-like regexp-like


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

      您可以使用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 是一个 dbfiddle。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-23
        • 1970-01-01
        • 2020-05-22
        • 1970-01-01
        • 2014-10-24
        • 2014-02-07
        • 2014-10-01
        • 2015-11-07
        相关资源
        最近更新 更多