【发布时间】:2018-07-11 17:51:23
【问题描述】:
https://www.db-fiddle.com/f/gZXz9hJRzpiEmDr7V8PXEG/0
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"}');
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 对象 - 仅包含 attributes 表中定义的键和 items.custom 列中的相应值。因此,将attributes 创建的一个 Json 对象与items.custom 数据合并是一种选择。
有没有办法在 Postgres 中做到这一点?
【问题讨论】:
标签: json postgresql jsonb