4

我有一个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

任何帮助,将不胜感激。

4

2 回答 2

3

您正在描述横向连接:

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
于 2020-08-24T20:33:50.523 回答
0

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

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;
于 2020-08-24T20:44:42.237 回答