如何从一个表中选择多行并插入到另一个表中特定行的特定jsonb字段中?但是在一个原始sql查询中

prdp8dxp  于 2021-08-13  发布在  Java
关注(0)|答案(1)|浏览(200)

博士后10.3
我在一个叫做 sites 如果我这样问

SELECT id, name from sites;

我要1000排。
我还有一张table叫 jsonindexdocument 其中一行的id为1,字段名为 index 那是jsonb
有没有可能在一个查询中,我取出sites表中的所有1000行,然后更新名为 index 身份证1以下?
json的格式是

[
  {
     "id": 10,
     "name": "somename"
  },
  {
     "id": 11,
     "name": "another name"
  } // and the rest of the 1000 rows
]

我也可以,如果它使用超过1个原始sql语句。

更新

我想补充一点,如果结果是空集,那么在json字段中默认为空数组

h43kikqp

h43kikqp1#

假设你可以完全替换 index 价值观 jsonindexdocument 表格:

UPDATE jsonindexdocument
SET index = (
    -- using json_agg(row_to_json(sites.*)) would also work here, if you want to copy
    -- all columns from the sites table into the json value
    SELECT COALESCE(json_agg(json_build_object(
        'id', id,
        'name', name
    )), '[]'::json)
    FROM sites
)
WHERE id = 1;

例如:

CREATE TEMP TABLE sites (
    id   INT,
    name TEXT
);

CREATE TEMP TABLE jsonindexdocument (
    id    INT,
    index JSON
);

INSERT INTO sites
VALUES (1, 'name1')
     , (2, 'name2');

INSERT INTO jsonindexdocument
VALUES (1, NULL);

UPDATE jsonindexdocument
SET index = (
    SELECT COALESCE(json_agg(json_build_object(
        'id', id,
        'name', name
    )), '[]'::json)
    FROM sites
)
WHERE id = 1;

SELECT * FROM jsonindexdocument;

退货

+--+------------------------------------------------------------+
|id|index                                                       |
+--+------------------------------------------------------------+
|1 |[{"id" : 1, "name" : "name1"}, {"id" : 2, "name" : "name2"}]|
+--+------------------------------------------------------------+

相关问题