Postgresql - 使用一个 table 中的 selected 列作为 json select 语句

Postgresql - Use selected column from one table as json select statements

https://www.db-fiddle.com/f/gZXz9hJRzpiEmDr7V8PXEG/0

PostgreSQL 10.x

考虑以下 table:

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 table 中的列作为 ìtems.custom 列中的 Json 键 - 所以查询总是 returns同一组键。

当我知道我会做的专栏时:

SELECT name, custom->>'sth1', custom->>'sth2' FROM items;

我想进行此查询 "dynamic" - 因此 attributes table.

中可以有任意键定义

对我来说也可以接受 table,在查询中创建一个新的 Json 对象 - 只包含 attributes table 中定义的键和items.custom 列中的相应值。因此,将 attributes 创建的一个 Json 对象与 items.custom 数据合并是一种选择。

有没有办法在 Postgres 中完成此操作?

您需要一个函数来动态格式化和执行 suitable 查询。函数 returns 行 name 和一个 jsonb 对象 data:

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)

因此这是您的第二个选择。第一个假设创建一种枢轴 table 并且需要更复杂的技术,例如参见