首页 > 解决方案 > 查询 postgresql jsonb 列中的内部字段

问题描述

我有一个 jsonb 列,其结构如下:

{
    .....other fields,
    "a" : {
        "b" : {
            "c" : "some value",
            ....other fields
        }
        .....other fields
    },
    ...other fields
}

我可以有这样的查询,属性是表 MyTable 中的列名:

SELECT * from
  MyTable t
WHERE t.properties @> '{"a":{"b":{"c": "some value"}}}';

但是“c”之前的字段可能不同,即我们可以有:

{
        .....other fields,
        "m" : {
            "n" : {
                "c" : "some value",
                ....other fields
            }
            .....other fields
        },
        ...other fields
    }

如何针对这种情况修改我的查询?

标签: postgresqljsonbpostgresql-12

解决方案


如果嵌套始终处于同一级别,则可以使用 JSON/Path 表达式:

select *
from the_table
where properties @@ '$.*.*.c == "some value"'

推荐阅读