gpt4 book ai didi

sql - 带有关系表的 Postgres tsvector

转载 作者:行者123 更新时间:2023-11-29 13:19:36 25 4
gpt4 key购买 nike

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

这里是 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 时,Product 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;

最佳答案

基本思想是在“parent_id”中加入 id 不是针对 null,而是“至少针对 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

关于sql - 带有关系表的 Postgres tsvector,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44285327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com