Postgres数组字段将字符串前置到每个数组元素

时间:2017-05-11 07:22:25

标签: sql postgresql

在PostgresDB中,我有一个数组字段,它看起来像这样 id | lesson | years 1 | math | {5,6} 2 | science | {4,5} 我如何预先附加一个字符串,将year说成年份字段中的每个项目,
select id, lesson, func_append_to_array_item(year) from table 它返回 id | lesson | years 1 | math | {year 5, year 6} 2 | science | {year 4, year 5}

1 个答案:

答案 0 :(得分:0)

如果您只想选择它,可以使用unnest + array_agg,例如:

t=# with c as (
  select id, lesson, concat('year ',unnest("year"))
  from "table"
)
select id, lesson,array_agg(concat) "year"
from c
group by id, lesson;
        year
---------------------
 {"year 5","year 6"}
(1 row)

但是如果你想更新实际字段,首先需要在数年列中将array []更改为array []文本。

请避免使用关系名称中的保留字。 yeartable都是SQL,而不仅仅是单词

<强>更新 OP一旦更新了帖子并反映了评论:

构建

t=# create table s125(id int, lesson text, years int[]);
CREATE TABLE
t=# insert into s125 values (1,'math','{5,6}'),(2,'science','{4,3}');
INSERT 0 2
t=# create or replace function s126(_y int[]) returns table (years text[]) as $$
begin
return query with c as (
  select concat('year ',unnest(_y))
)
select array_agg(concat) "years"
from c
;
end;
$$ language plpgsql;
CREATE FUNCTION

运行:

t=# select id,lesson,s126(years) from s125;
 id | lesson  |        s126
----+---------+---------------------
  1 | math    | {"year 5","year 6"}
  2 | science | {"year 4","year 3"}
(2 rows)