【问题标题】:Postgresql merge columnsPostgresql 合并列
【发布时间】:2022-01-26 09:49:15
【问题描述】:

我有一个像这样的主表

CREATE TABLE IF NOT EXISTS people 
(
    country text,
    full_name text,
    last_name text,
    children_names text[]
);

INSERT INTO people (country, full_name, last_name, children_names) 
VALUES ('de', 'han', 'post', '{"joe", "joe1", "joe2", "joe3"}');

我可以像这样合并full_namelast_name

SELECT
    full_name || '_' || last_name AS obid
FROM 
    people;

但我无法对 children_names 列做同样的事情,我想选择这样的孩子

select children_names 
from people;

但我想像这样在每个孩子的末尾添加 last_name 字段

{joe_han,joe1_han,joe2_han,joe3_han}

【问题讨论】:

标签: sql postgresql


【解决方案1】:

使用标量子查询:

SELECT
  full_name||'_'||last_name obid, 
  (select array_agg(u||'_'||full_name) from unnest(children_names) u) children
FROM people;

然而,按照@BarbarosÖzhan 的建议构建数据会更好。

【讨论】:

    【解决方案2】:

    您应该使用unnest 函数提取数据,然后添加last_name 列。合并数据后,你必须使用聚合来创建一个数组。

    Demo

    SELECT
        full_name || '_' || last_name as obid,
        array_agg(value || '_' || last_name)
    FROM people CROSS JOIN unnest(children_names) value
    GROUP BY 1;
    

    【讨论】:

    • 这可能比加入更快,我无法测试,因为我现在没有 pg 系统:SELECT ARRAY(SELECT cn || '_' || last_name FROM UNNEST(children_names) cn) FROM people;
    猜你喜欢
    • 1970-01-01
    • 2012-08-19
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 2017-11-24
    • 2012-02-28
    • 2017-11-04
    相关资源
    最近更新 更多