首页 > 解决方案 > 获取值为 true 的 postgresql 表中 jsonb 对象的所有键

问题描述

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

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

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

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

这篇文章中,我了解到

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

任何帮助,将不胜感激。

标签: arraysjsonpostgresqlunnestlateral-join

解决方案


您正在描述横向连接:

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

推荐阅读