【问题标题】:Postgres join on jsonb array that contains Key:value pair in another jsonb arrayPostgres 加入 jsonb 数组,该数组包含另一个 jsonb 数组中的键:值对
【发布时间】:2021-08-09 20:00:34
【问题描述】:

此 SQL 有效,但我需要搜索数组中的所有值,而不是仅加入数组中的第一个值。

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 值=酒吧。

给我所有的遭遇记录,其中“帐户”数组包含和项目也包含在帐户记录的“标识符”数组中,并且该帐户记录具有 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}'))

但这感觉很脏。

【问题讨论】:

  • 请提供样本数据和所需的输出
  • 更新了更多信息@eshirvana

标签: arrays json postgresql join


【解决方案1】:

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

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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 2021-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-14
    相关资源
    最近更新 更多