获取 postgresql table 中值为 true 的 jsonb 对象的所有键
Get all keys of jsonb object in postgresql table where value is true
我有一个带有 name
和 features
列的 postgresql table customers
。
features
包含像 {"featureA": true, "featureB": false, "featureC":true}
这样的 jsonb 对象
我想要得到的是 features
中那些键的数组,其中每个 name
的值都是真实的,例如:
name | features
----------|---------------------
customerA | [featureA, featureC]
customerB | [featureB, featureC]
从得知
SELECT key
FROM jsonb_each()
WHERE value = jsonb 'true'
是您获得真实密钥的方式,但我如何为我的 table customers
做到这一点?
类似
SELECT array_agg(key)
FROM jsonb_each((select features from customers))
WHERE value = jsonb 'true'
returns SQL Error [21000]: ERROR: more than one row returned by a subquery used as an expression
.
如有任何帮助,我们将不胜感激。
您描述的是横向连接:
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
也可以像这样在 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;
我有一个带有 name
和 features
列的 postgresql table customers
。
features
包含像 {"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'
是您获得真实密钥的方式,但我如何为我的 table customers
做到这一点?
类似
SELECT array_agg(key)
FROM jsonb_each((select features from customers))
WHERE value = jsonb 'true'
returns SQL Error [21000]: ERROR: more than one row returned by a subquery used as an expression
.
如有任何帮助,我们将不胜感激。
您描述的是横向连接:
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
也可以像这样在 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;