【问题标题】:Get all keys of jsonb object in postgresql table where value is true获取值为 true 的 postgresql 表中 jsonb 对象的所有键
【发布时间】:2020-12-13 11:54:33
【问题描述】:

我有一个带有 namefeatures 列的 postgresql 表 customers

features 包含 jsonb 对象,例如 {"featureA": true, "featureB": false, "featureC":true}

我想要得到的是 features 中的这些键的数组,其中每个 name 的值都为 true,例如:

name      | features
----------|---------------------
customerA | [featureA, featureC]
customerB | [featureB, featureC]

this post得知

SELECT key
FROM jsonb_each()
WHERE value = jsonb 'true'

您是如何获得正确的密钥的,但我该如何为我的表 customers 做到这一点?

类似

SELECT array_agg(key)
FROM   jsonb_each((select features from customers))
WHERE  value = jsonb 'true'

返回SQL Error [21000]: ERROR: more than one row returned by a subquery used as an expression

任何帮助将不胜感激。

【问题讨论】:

    标签: arrays json postgresql unnest lateral-join


    【解决方案1】:

    您正在描述横向连接:

    select c.name, x.keys
    from customers c
    cross join lateral (
        select array_agg(x.key) keys
        from jsonb_each(c.features) x
        where x.value = jsonb 'true'
    ) x
    

    【讨论】:

      【解决方案2】:

      也可以像这样在 select 子句中使用jsonb_each()

      select
          x.name,
          json_agg(x.feature_name) as features
      from (
          select
              c.name,
              row_to_json(jsonb_each(c.features))->>'key' as feature_name,
              (row_to_json(jsonb_each(c.features))->>'value')::bool as value
          from customers c
      ) as x
      where x.value
      group by x.name;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-24
        • 2018-06-23
        • 1970-01-01
        • 2019-09-24
        • 2017-06-23
        • 2021-11-23
        • 1970-01-01
        • 2019-09-26
        相关资源
        最近更新 更多