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

如何从一个表中选择多行并插入到另一个表中特定行的特定JSONB字段中?但是在单个原始SQL查询中,sql,arrays,json,postgresql,Sql,Arrays,Json,Postgresql,博士后10.3 我在一个名为sites 如果我这样问 SELECT id, name from sites; 我要1000行 我还有另一个名为jsonindexdocument的表,其中有一行id为1,还有一个名为index的字段,即JSONB 是否有可能在一次查询中,我取出sites表中的所有1000行,然后更新id 1下名为index的字段 json的格式应该是 [ { "id": 10, "name": "somename" }, { "id":

博士后10.3

我在一个名为
sites

如果我这样问

SELECT id, name from sites;
我要1000行

我还有另一个名为
jsonindexdocument
的表,其中有一行id为1,还有一个名为
index
的字段,即JSONB

是否有可能在一次查询中,我取出sites表中的所有1000行,然后更新id 1下名为
index
的字段

json的格式应该是

[
  {
     "id": 10,
     "name": "somename"
  },
  {
     "id": 11,
     "name": "another name"
  } // and the rest of the 1000 rows
]
如果它使用多个原始SQL语句,我也可以

更新
我想补充一点,如果结果为空集,那么假设您可以完全替换
jsonindexdocument
表中的
index
值,那么json字段默认为空数组:

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"}]|
+--+------------------------------------------------------------+

谢谢我用它做实验后,它会被标记为正确的。我今天下班。那么明天我们就要考试了。谢谢:)谢谢你,玛斯。你的答案是厨师之吻!我在单元测试中遇到了一个罕见的空集,因此我编辑了您的答案以包含coalesce。我还更新了我的问题,以反映这一需要。仅供参考。