Postgres 加入包含另一个 jsonb 数组中的 Key:value 对的 jsonb 数组

时间:2021-05-20 14:35:03

标签: arrays json postgresql join

这个 SQL 可以工作,但我需要搜索数组中的所有值,而不是仅加入遇到.document -> 帐户中数组中的第一个值。

SELECT encounter.* FROM encounter JOIN account
ON (account.document -> 'identifier') @> jsonb_build_array(jsonb_build_object('value', encounter.document #> '{account, 0, identifier, value}', 'system', encounter.document #> '{account, 0, identifier, system}')
WHERE account.foo = 'bar'

例会:

encounter.document = {"account": [{"system": "foo", "value": "bar"}, {"system": "two-foo", "value": "two-bar"}]}

示例帐户:

account.foo = bar
account.document = {"identifier": [{"system": "foo", "value": "bar"}, {"system": "blah", "value": "blah"}]}

鉴于上述记录,我希望能取回遭遇记录,因为遭遇记录中的“帐户”数组包含一个对象,该对象位于帐户记录的“标识符”数组中,并且该帐户记录具有 foo 值= 酒吧。

给我所有遭遇记录,其中“account”数组包含,项目也包含在帐户记录的“identifier”数组中,并且该帐户记录有 foo = bar - 将是另一种放置方式。

如果我在增加数组索引的 on 子句中添加几个 OR 似乎可以做到:

ON ((account.document -> 'identifier') @> jsonb_build_array(jsonb_build_object('value', encounter.document #> '{account, 0, identifier, value}', 'system', encounter.document #> '{account, 0, identifier, system}')
OR(account.document -> 'identifier') @> jsonb_build_array(jsonb_build_object('value', encounter.document #> '{account, 1, identifier, value}', 'system', encounter.document #> '{account, 1, identifier, system}'))

但这感觉很脏。

1 个答案:

答案 0 :(得分:0)

使其更通用和防弹的一种方法是:

select a.*
from(
        select *
        from encounter e
        cross join jsonb_to_recordset(jsonb_extract_path(e.document, 'account')) as x (value varchar(100), system varchar(100))
    ) a
    join (
        select *
        from account a
        cross join jsonb_to_recordset(jsonb_extract_path(a.document, 'identifier')) as y (value varchar(100), system varchar(100))
    ) b on a.value = b.value
    and a.system = b.system
    and a.value = 'foo'
    and a.system = 'bar'
相关问题