Postgresql-使用一个表中的选定列作为json select语句
Postgresql 10.x 考虑下表:Postgresql-使用一个表中的选定列作为json select语句,json,postgresql,jsonb,Json,Postgresql,Jsonb,Postgresql 10.x 考虑下表: CREATE TABLE attributes ( attr TEXT ); INSERT INTO attributes VALUES('sth1'); INSERT INTO attributes VALUES('sth2'); CREATE TABLE items ( name TEXT, custom JSONB ); INSERT INTO items VALUES ('A', '{"sth1": "Hello"
CREATE TABLE attributes (
attr TEXT
);
INSERT INTO attributes VALUES('sth1');
INSERT INTO attributes VALUES('sth2');
CREATE TABLE items (
name TEXT,
custom JSONB
);
INSERT INTO items VALUES ('A', '{"sth1": "Hello"}');
INSERT INTO items VALUES ('B', '{"sth1": "Hello", "sth2": "Okay"}');
INSERT INTO items VALUES ('C', '{"sthNOT": "Hello", "sth2": "Okay"}');
我的目标是只查询attributes
表中列作为ìtems.custom
列中的Json键-因此查询总是返回相同的键集
当我知道这些专栏时,我只会:
SELECT name, custom->>'sth1', custom->>'sth2' FROM items;
我想让这个查询成为“动态的”——这样就可以在attributes
表中定义任意键
对我来说,在查询中创建一个新的Json对象也是可以接受的——只包含属性表中定义的键以及items.custom
列中相应的值。因此,可以选择将从属性创建的一个Json对象与项进行合并
有没有办法在Postgres中实现这一点?您需要一个函数来动态格式化和执行合适的查询。该函数返回带有名称的行和一个jsonb对象数据的行
:
create or replace function select_from_items()
returns table(name text, data jsonb) language plpgsql as $$
declare
cols text;
begin
select string_agg(format('%1$L, custom->>%1$L', attr), ', ')
from attributes
into cols;
return query execute format('
select name, jsonb_strip_nulls(jsonb_build_object(%s))
from items', cols);
end $$;
select * from select_from_items();
name | data
------+-----------------------------------
A | {"sth1": "Hello"}
B | {"sth1": "Hello", "sth2": "Okay"}
C | {"sth2": "Okay"}
(3 rows)
因此,这是你的第二个选择。第一种方法假设创建一种透视表,需要更复杂的技术,请参见
- 或
感谢您的详细回答!非常感谢。