我有两张这样的表:
create table product (
id serial primary key,
name text
);
create table selectedattribute (
id serial primary key,
product integer references product,
attribute text,
val text
);
我正在使用此选择查询创建实体化视图
select product.name,
jsonb_build_object(
'color', COALESCE(jsonb_agg(val) FILTER (WHERE attribute='color'), '[]'),
'diameter', COALESCE(jsonb_agg(val) FILTER (WHERE attribute='diameter'), '[]')
)
from product
left join selectedattribute on product.id = selectedattribute.product
group by product.id;
此选择查询的问题是当我添加新属性时,我必须将其添加到选择查询以创建最新的物化视图。
有没有办法编写一个聚合表达式,动态获取没有所有这些硬编码属性名称的属性?
您可以在SQL小提琴中尝试我的代码:http://sqlfiddle.com/#!17/c4150/4
答案 0 :(得分:1)
您需要嵌套聚合。首先收集属性的所有值,然后将其聚合为JSON:
select id, name, jsonb_object_agg(attribute, vals)
from (
select p.id, p.name, a.attribute, jsonb_agg(a.val) vals
from product p
left join selectedattribute a on p.id = a.product
group by p.id, a.attribute
) t
group by id, name;
更新了SQLFiddle:http://sqlfiddle.com/#!17/c4150/5