我对此进行了很多研究,但仍然无法回答.我在用PostgreSQL.在下面的示例中,列名是"sections",列类型是json[].

我的专栏在数据库中看起来像这样:

sections
[{"name"      : "section1",
  "attributes": [{"attrkey1": "value1",
                  "attrkey2": "value2"},

                 {"attrkey3": "value3",
                  "attrkey4": "value4"}]
 },
 {"name"      : "section2",
  "attributes": [{"attrkey3": "value5",
                  "attrkey6": "value6"},

                 {"attrkey1": "value7",
                  "attrkey8": "value8"}]
 }]

这是json数组,我想在结果中得到"attrkey3".为了从Json获取特定的密钥,我可以使用json_extract_path_text(json_column, 'json_property'),这非常好.但我不知道如何从json[]获取一些属性.

如果我讨论上面的例子,我想在结果中显示属性"attrkey2"的值.我知道这是一个数组,因此它的工作方式可能与通常的不同,例如,我的数组的所有值都将作为不同的行,因此我可能必须编写子查询,但不知道如何执行.

此外,我不能静态地编写索引,也不能从某个特定的索引中获取json元素的属性.我的查询将动态生成,所以我永远不会知道json数组中有多少元素.

我看到了一些静态示例,但不知道如何在我的 case 中实现它.有人能告诉我怎么做吗?

推荐答案

我不确定您是否有一个json[](json个值的PostgreSQL数组)类型的列,或者一个json类型的列,它似乎是一个JSON数组(如您的示例中所示).

无论哪种情况,都需要在查询之前扩展array.如果是json[],则需要使用unnest(anyarray);对于json类型列中的JSON数组,需要使用json_array_elements(json)(和LATERAL个连接——在我的示例中它们是隐式的):

select     t.id,
           each_section ->> 'name' section_name,
           each_attribute ->> 'attrkey3' attrkey3
from       t
cross join unnest(array_of_json) each_section
cross join json_array_elements(each_section -> 'attributes') each_attribute
where      (each_attribute -> 'attrkey3') is not null; 
-- use "where each_attribute ? 'attrkey3'" in case of jsonb


select     t.id,
           each_section ->> 'name' section_name,
           each_attribute ->> 'attrkey3' attrkey3
from       t
cross join json_array_elements(json_array) each_section
cross join json_array_elements(each_section -> 'attributes') each_attribute
where      (each_attribute -> 'attrkey3') is not null;

SQLFiddle

不幸的是,您不能对数据使用任何索引.为了做到这一点,您需要首先修复模式.

Postgresql相关问答推荐

锁定模式与PostgreSQL中的另一种锁定模式冲突到底是什么意思?

在PostgreSQL中,`MY_VARIABLE IN(<;Long_ARRAY_of_Items>;)`何时是FAST?

PL/pgSQL 中 PL/SQL %ISOPEN 的类似功能是什么?

无法从 docker-compose 上的其他服务解析 postgres 主机名

Regexp_replace 行为会改变,如果它用空白字符串或 null 替换字符串数组中的字符串

从 Postgres 字段中的多个值中进行 Select

如何从元组列表中 Select 与多列匹配的行?

从左连接更新 Postgres

postgresql 在查询中插入空值

PostgreSQL 不区分大小写的 SELECT 数组

Psycopg2 使用占位符插入表格

如何使用 psql 命令列出、创建、使用和判断数据库?

使用 current_setting() 判断值

如何禁用 postgresql缓存优化?

子查询的自连接

无法在 postgresql hibernate 中使用名为user的表

大型查询后 psycopg2 泄漏内存

PostgreSQL 中跨多个表的索引

如何减少存储(缩减)我的 RDS 实例?

如何在创建数据库时安装 Postgres 扩展?