gpt4 book ai didi

sql - 查询在 postgres jsonb 中相交的 json 键

转载 作者:行者123 更新时间:2023-11-29 14:30:50 27 4
gpt4 key购买 nike

我如何查询相交的 jsonb 键:

例如:

     kv                                 |        column1                   
-----------------------------------------------------------
[{"k1": "v1"}, {"k2": "v22"}] | web
[{"k10": "v5"}, {"k9": "v21"}] | mobile
[{"k1": "v1"}, {"k5": "v24"}] | web1
[{"k5": "v1"}, {"k55": "v24"}] | web1

这里,第 1 行和第 3 行有键 k1,第 3 行和第 4 行有键 k5

所以,答案应该是第 1、3 和 4 行。

最佳答案

假设以下设置:

create table data (id serial, kv jsonb, col1 text);

insert into data (kv, col1)
values
('[{"k1": "v1"}, {"k2": "v22"}]', 'web'),
('[{"k10": "v5"}, {"k9": "v21"}]', 'mobile'),
('[{"k1": "v1"}, {"k5": "v24"}]', 'web1'),
('[{"k5": "v1"}, {"k55": "v24"}]', 'web1');

您可以通过首先对数据进行规范化,然后对规范化数据进行自联接来获取这些行。要规范化数据,您需要取消嵌套 JSON 值两次:一次用于展平数组,另一次用于从 JSON 值中提取键:

with normalized as (
select d.id, t2.*
from data d
join jsonb_array_elements(kv) as t1(kv) on true
join jsonb_each_text(t1.kv) as t2(k,val) on true
)
select n1.*
from normalized n1
where exists (select *
from normalized n2
where n1.id <> n2.id
and n1.k = n2.k);

以上返回:

id | k  | val
---+----+----
1 | k1 | v1
3 | k1 | v1
3 | k5 | v24
4 | k5 | v1

或者将其与 IN 条件一起使用以获取原始行:

with normalized as (
select d.id, t2.*
from data d
join jsonb_array_elements(kv) as t1(kv) on true
join jsonb_each_text(t1.kv) as t2(k,val) on true
)
select *
from data
where id in (select n1.id
from normalized n1
where exists (select *
from normalized n2
where n1.id <> n2.id
and n1.k = n2.k))

返回:

id | kv                             | col1
---+--------------------------------+-----
1 | [{"k1": "v1"}, {"k2": "v22"}] | web
3 | [{"k1": "v1"}, {"k5": "v24"}] | web1
4 | [{"k5": "v1"}, {"k55": "v24"}] | web1

如果您不将键/值对存储在数组中,这种类型的查询会更容易,'{"k1": "v1", "k2": "v22"}' 对我来说比 [{"k1": "v1"}, {"k2": "v22"}]

更有意义

关于sql - 查询在 postgres jsonb 中相交的 json 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52110083/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com