我有两张简单的桌子。首先是品牌,每个品牌都可能有一个顶级品牌。例如 Elseve 有一个顶级品牌是 Loreal Paris。但雅芳没有顶级品牌。我有一个简单的产品表。
这是品牌表。
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 文档返回空结果。但我需要在文档中至少获得雅芳。
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;