如何将带有数组的普通值转换为 PostgreSQL 中的数据结构?

How to convert plain values with arrays into a data structure in PostgreSQL?

我有这个从“作者 + 文章”值列表开始的演示查询:

VALUES
('author1', ARRAY[('title1', 'content1'), ('title2', 'content2')]),
('author2', ARRAY[('title3', 'content3'), ('title4', 'content4')])

我想将其转换为以下数据结构:

author title content
author1 title1  content1
author1  title2 content2
author2 title3  content3
author2 title4  content4

我已经走到这一步了:

WITH "raw_data" ("author", "articles") AS  (
    VALUES
        ('author1', ARRAY[('title1', 'content1'), ('title2', 'content2')]),
        ('author2', ARRAY[('title3', 'content3'), ('title4', 'content4')])
),
"articles" AS (
    SELECT "author", unnest("articles") AS "article" FROM "raw_data"
)
SELECT author, article FROM "articles";

但我得到以下信息:

author article
author1 (title1, content1)
author1  (title2, content2)
author2 (title3, content3)
author2 (title4, content4)

我需要找到一种方法将记录 (title2, content1) 转换为 2 个不同的列。

谢谢大家!

您可以通过为您的记录创建自定义类型并将其强制转换来实现此目的。

参见下面的示例

模式(PostgreSQL v13)


查询#1

create type article as (title text, contents text);

没有要显示的结果。


查询#2

WITH "raw_data" ("author", "articles") AS  (
    VALUES
        ('author1', ARRAY[('title1', 'content1'), ('title2', 'content2')]),
        ('author2', ARRAY[('title3', 'content3'), ('title4', 'content4')])
),
"articles"  AS (
    SELECT "author", ((unnest("articles"))::text::article).* FROM "raw_data"
)
SELECT * FROM "articles";
author title contents
author1 title1 content1
author1 title2 content2
author2 title3 content3
author2 title4 content4

View on DB Fiddle

只是分解表达式 ((unnest("articles"))::text::article).*

  1. (unnest("articles") - 将数组转换为行
  2. ((unnest("articles"))::text - 将每条记录转换为文本(此时无法直接转换为文章)
  3. (unnest("articles"))::text::article - 将每条记录投射到您的文章类型
  4. ((unnest("articles"))::text::article).* - 展开或select 全部从您的记录中获取两列

让我知道这是否适合你