2016-09-20 106 views
0

我想查找兩個表之間的匹配詞。 此查詢運作良好,但我想獲得完全匹配的單詞以及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

可能有其他的方法,但這裏是一個:

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; 

如果它不爲你工作,那麼有可能是字符集問題還是人品不好僞裝,比如說,如空間。

+0

感謝它的工作。 :) 當你說其他方法, 你的意思是可能有更快或不必要的其他方法! – Raha1986

+0

但它不返回所有匹配的單詞!它發現第一場比賽時停止! – Raha1986

+0

@ Raha1986。 。 。這可能是您打印數組的方式。也許你應該使用'string_agg()'而不是'array_agg()'。 –

相關問題