postgresql - 将一组 JSON 对象合并到 Postgres 中的一个 JSON 列

标签 postgresql postgresql-10

我有两个表,productsproducts_ext 可以从根本上减少 到这个基本形式:

CREATE TABLE "products" (
  "product_id" TEXT PRIMARY KEY
);

CREATE TABLE "products_ext" (
  "product_id" TEXT NOT NULL,
  "key" TEXT NOT NULL,
  "value" JSON,
  PRIMARY KEY ("product_id", "key"),
  FOREIGN KEY ("product_id") REFERENCES "products"("product_id")
    ON DELETE CASCADE
    ON UPDATE CASCADE
  );

让我们假设模拟数据

INSERT INTO "products" ("product_id") VALUES
  ('test1'),
  ('test2'),
  ('test3');

INSERT INTO "products_ext" (product_id, "key", "value") VALUES
  ('test1', 'foo', '"Foo"'),
  ('test1', 'bar', '"Bar"'),
  ('test2', 'foo', '"Foo"');

我可以使用查询

SELECT
  "P"."product_id",
  ARRAY(
    SELECT
      json_build_object(
        "E"."key",
        "E"."value"
      )
    FROM "products_ext" AS "E"
    WHERE "E"."product_id" = "P"."product_id"
  )
FROM
  "products" AS "P";

产生

product_id |                     array                     
------------+-----------------------------------------------
test1      | {"{\"foo\" : \"Foo\"}","{\"bar\" : \"Bar\"}"}
test2      | {"{\"foo\" : \"Foo\"}"}

但我无法生成合并的 JSON。 Postgres 10 中有简单的方法吗 将多个 JSON 的数组合并为一个 JSON 会产生?

product_id |                   json                
------------+----------------------------------------
test1      | {\"foo\" : \"Foo\", \"bar\" : \"Bar\"}
test2      | {\"foo\" : \"Foo\"}
test3      | {}

主键对“product_id”和“key”已经确定没有 按键碰撞。 products 中可能有一些行在 products_ext 中没有任何数据,在这种情况下,应该提供一个空的 JSON 对象。

最佳答案

demo:db<>fiddle

使用json_object_agg():

SELECT
  p.product_id AS product_id,
  json_object_agg(e.key, e.value)
FROM
  products AS p
JOIN
  products_ext AS e ON p.product_id = e.product_id
GROUP BY p.product_id;

编辑空 product_ext 值:

demo:db<>fiddle

SELECT
  p.product_id AS product_id,
  COALESCE(
      json_object_agg(e.key, e.value) FILTER (WHERE e.key IS NOT NULL),
      '{}'
  )
FROM
  products AS p
LEFT JOIN
  products_ext AS e ON p.product_id = e.product_id
GROUP BY p.product_id;

关于postgresql - 将一组 JSON 对象合并到 Postgres 中的一个 JSON 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57496120/

相关文章:

database - 这是将远程数据库复制到开发中最安全的方法吗?

sql - 为每个等级取一批记录,然后加入,然后在 postgres 中限制 1

python - 我可以检索 macaddr8 列作为数字吗?

postgresql - 升级到想要使用校验和的 postgres 10

PostgreSQL 10 : How to delete orphan rows in Table A on only IDs existing in Table B?

postgresql - 无法在数据类型为 reltime 的 postgres 字段中输入日期

linux - 使用 Navicat 通过 SSH 登录 Postgresql - 正确的设置是什么?

ruby-on-rails-3 - Ruby on Rails 使用 PostgreSQL 进行计数和分组

sql - 从函数返回记录集(虚拟表)

sql - PostgreSQL 10 Rowtype 功能错误?