【问题标题】:Count matching words between two strings in Postgres?计算Postgres中两个字符串之间的匹配词?
【发布时间】:2021-02-15 00:31:39
【问题描述】:

我想根据两个字符串中匹配单词的数量对结果进行排序(不区分大小写)。有没有办法给两个字符串来计算两个字符串中出现的匹配单词的数量?

例子:

"Red blue black green", "Green Black Blue"
-> 3
"Blue Green", "green blue"
-> 2
"Blue Green", "Red blue"
-> 1
"green blue black", "orange purple"
-> 0

我想在 Order By 子句中使用它。假设一个表有一个包含字符串的列,我将查询该表,然后根据传入的字符串中匹配单词最多的行对结果进行排序。

【问题讨论】:

    标签: sql string postgresql count lateral-join


    【解决方案1】:

    您可以使用regexp_split_to_table() 将两个短语拆分为单词,然后计算匹配项。为此,横向连接很方便。

    select t.*, x.cnt_matches
    from (values 
        ('Red blue black green', 'Green Black Blue'),
        ('Blue Green',           'green blue'),
        ('Blue Green',           'red blue'),
        ('green blue black',     'orange purple')
    ) as t(str1, str2)
    cross join lateral (
        select count(*) cnt_matches
        from regexp_split_to_table(lower(t.str1), ' ') w1(word)
        inner join regexp_split_to_table(lower(t.str2), ' ') w2(word)
            on w1.word = w2.word
    ) x
    

    Demo on DB Fiddle

    str1 | str2 | cnt_matches :-------------------- | :--------------- | ----------: 红蓝黑绿|绿色 黑色 蓝色 | 3 蓝绿 |绿蓝| 2 蓝绿 |红蓝| 1 绿蓝黑|橙紫| 0

    【讨论】:

    • 有没有办法在 order by 子句中做到这一点?在我的表中有一个包含字符串的字段,当我进行查询时,我想传入一个字符串,然后按表列上匹配单词的数量对结果进行排序。
    • @PeterR:这是相同的逻辑。您也可以在order by 子句中使用cnt_matches
    猜你喜欢
    • 1970-01-01
    • 2014-06-28
    • 2013-10-16
    • 2018-11-07
    • 1970-01-01
    • 2017-04-02
    • 2015-04-08
    • 2023-03-11
    • 1970-01-01
    相关资源
    最近更新 更多