带有关系表的 Postgres tsvector

Postgres tsvector with relational tables

我有两个简单的 table。首先是品牌,每个品牌可能都有一个顶级品牌。例如,Elseve 有一个顶级品牌,即 Loreal Paris。但雅芳没有顶级品牌。我有一个简单的产品 table.

这里是sqlfiddle

这是品牌 table。

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

这是产品 table

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

当我尝试获取 tsvectors 时,Product 1 文档 returns 为空结果。但我至少需要在文档中获得雅芳。

 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;

基本思想是在 "parent_id" 中加入 id,而不是针对 null,而是 "at least against id",正如我从您的 post 那里得到的那样。 喜欢这里:

   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