您如何在一个带有ID的select语句中组合两个jsonb对象?

时间:2019-06-21 10:35:35

标签: postgresql

我是PostgresSQL上jsonb操作的新手。我的数据库中有两个表,一个表嵌套在其中,另一个表的ID包含一个json blob:

'Content-Type: multipart/form-data; boundary=---------------------------7da24f2e50046'
Table A
id | content
1  | { oneKey: "something", params: {anotherKey: "something", tableBEntries: [1,2]}}
2  | { oneKey: "something2", params: {anotherKey: "something2", tableBEntries: [3]}}
...

我想从表A中选择条目,然后将它们与表B合并,以便结果如下:

Table B
id | content
1  | {someKeysB: "values", anotherKeyB: "values"}
2  | {someKeysB: "values2", anotherKeyB: "values2"}
3  | {someKeysB: "values3", anotherKeyB: "values3"}

但是,在一个简单的Result id | content 1 | { oneKey: "something", params: {anotherKey: "something", tableBEntries: [{someKeysB: "values", anotherKeyB: "values"}, {someKeysB: "values2", anotherKeyB: "values2"}]}} 2 | { oneKey: "something2", params: {anotherKey: "something2", tableBEntries: [{someKeysB: "values3", anotherKeyB: "values3"}]}} 语句上,我找不到做到这一点的方法……只能提取select

tableBEntries

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

step-by-step demo:db<>fiddle

SELECT
    jsonb_set(content, ARRAY['params','tableBEntries'], agg)                         -- 4
FROM (
    SELECT 
        a.*,
        jsonb_agg(b.content) AS agg                                                  -- 3
    FROM
        a,
        jsonb_array_elements_text(content -> 'params' -> 'tableBEntries') as entries -- 1
    JOIN                                                                             -- 2
        b ON entries.value::int = b.id
    GROUP BY a.id, a.content 
) s
  1. 将数组每个元素扩展为一行
  2. 针对id中的b加入这些元素
  3. 与{a {1}}相关的记录的分组内容
  4. 用聚合的b值替换b元素