2017-05-31 38 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

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