2017-05-31 37 views
1

我有兩個簡單的表。首先是品牌,每個品牌都可能有頂級品牌。例如Elseve擁有一個名爲Loreal Paris的頂級品牌。但雅芳沒有頂級品牌。我有一個簡單的產品表。Postgres tsvector與關係表

這是sqlfiddle

這裏是品牌表。

id |  name  | parent_id | depth 
----+--------------+-----------+------- 
    3 | Loreal Paris |  null |  0 
    1 | Avon   |  null |  1 
    2 | Elseve  |  3 |  1 
(3 rows) 

這裏是產品表

id | brand_id | name 
----+----------+----------- 
    1 |  1 | Product 1 
    2 |  2 | Product 2 
(2 rows) 

當我試圖讓tsvectors,產品1號文件返回null結果。但我需要在文件中至少得到Avon。

product_id | product_name |      document 
------------+--------------+-------------------------------------------------- 
      1 | Product 1 | 
      2 | Product 2 | '2':2 'elsev':3 'loreal':4 'paris':5 'product':1 
(2 rows) 

如何解決這個問題?

感謝Voa Tsun。我更新了一些查詢。我不需要再分組了。

select 
    products.id as product_id, 
    products.name as product_name, 
    to_tsvector(products.name) || 
    to_tsvector(brands.name) || 
    to_tsvector(top_brands.name) 
    as document 
from products 
    JOIN brands on brands.id = products.brand_id 
    LEFT JOIN brands as top_brands on coalesce(brands.parent_id,brands.id) = top_brands.id; 
+0

你需要使用'COALESCE()'的地方,因爲'to_tsvector()''返回上NULL''NULL'輸入。參見f.ex. [文檔如何使用多列](https://www.postgresql.org/docs/current/static/textsearch-controls.html)。 – pozs

+0

http://rextester.com/SQVSTS56141喜歡這裏?.. –

+0

嗨@pozs。我已經使用過它。像這樣to_tsvector(coalesce(string_agg(top_brands.name,'')))。我知道這是不合邏輯的。因爲雅芳沒有top_brand記錄。所以它沒用。如果我爲所有品牌添加top_brand,併爲沒有top_brand的品牌清空top_brand名稱記錄,它將起作用。 –

回答

1

的基本思想是加入ID不反對在空「PARENT_ID」,但「至少對ID」,因爲我從您的文章得到。 喜歡這裏:

select 
     products.id as product_id, 
     products.name as product_name, 
     to_tsvector(coalesce(products.name,brands.name)) || 
     to_tsvector(brands.name) || 
     to_tsvector(coalesce(string_agg(top_brands.name, ' '))) 
     as document 
    from products 
     JOIN brands on brands.id = products.brand_id 
     LEFT JOIN brands as top_brands on coalesce(brands.parent_id,brands.id) = 
    top_brands.id 
    GROUP BY products.id,brands.id; 

    product_id product_name document 
1 1 Product 1 '1':2'avon':3,4'product':1 
2 2 Product 2 '2':2'elsev':3'loreal':4'pari':5'product':1 
+0

是的。它的作用就像一種魅力。 –