我有两个简单的表格。首先是品牌,每个品牌都可能拥有顶级品牌。例如,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时,Product 1文档返回null结果。但我需要在文件中至少获得雅芳。
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 :(得分:1)
基本的想法是在" parent_id"中加入id而不是null,但是#34;至少对于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