从搜索查询中返回匹配单词

时间:2016-09-20 12:42:02

标签: sql regex postgresql

我想在两张桌子之间找到匹配词。 此查询效果很好,但我想获得完全匹配的单词以及ID。

SELECT id
FROM debug_fullText
where title ~~* any (select matchWords from debug_matchWords)

这里是debug_fullText:

id        |title        |tags                                    |description
3893382135|"Tate Modern"|"london;londra;nut;squirrel;Westminster"|"Later that day I got to thinking about relationships.

并且匹配词是:

id|words
1 |"Westminister"
2 |"Tate Modern"
3 |"South Afrika"
4 |"London"

1 个答案:

答案 0 :(得分:1)

可能还有其他方法,但这里有一个:

SELECT ft.id, mw.words
FROM debug_fullText ft, lateral
     (select array_agg(matchword) as words, count(*) as cnt
      from debug_matchwords
      where title ilike matchWord
     ) mw
where mw.cnt > 0;

以下是一个例子:

with debug_fulltext as (
      select 1 as id, 'a b c'::text as title
     ),
     debug_matchwords(matchword) as (
      values ('%a%'::text), ('%b%')
     )
select ft.id, mw.words
from debug_fullText ft, lateral
     (select array_agg(matchword) as words, count(*) as cnt
      from debug_matchwords
      where title ilike matchWord
     ) mw
where mw.cnt > 0;

这会返回两个单词。

编辑II:

这将为我返回匹配:

with debug_fulltext as (
      select 3893382135 as id, 'Tate Modern'::text as title
     ),
     debug_matchwords(id, matchword) as (
      values (1, 'Westminister'),
             (2 , 'Tate Modern'),
             (3 , 'South Afrika'),
             (4 , 'London')
     )
SELECT ft.id, mw.words
FROM debug_fullText ft, lateral
     (select array_agg(matchword) as words, count(*) as cnt
      from debug_matchwords
      where title ilike matchWord
     ) mw
where mw.cnt > 0;

如果它对您不起作用,则可能存在字符集问题或伪装成字符,例如,作为空格。