簡體   English   中英

Postgres數組字段在每個數組元素前添加字符串

[英]Postgres array field prepend string to each of the array element

在PostgresDB中,我有一個數組字段,它看起來像這個id | lesson | years 1 | math | {5,6} 2 | science | {4,5} id | lesson | years 1 | math | {5,6} 2 | science | {4,5} id | lesson | years 1 | math | {5,6} 2 | science | {4,5}我如何在Years字段中的每個項目前附加一個字符串,例如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} id | lesson | years 1 | math | {year 5, year 6} 2 | science | {year 4, year 5}

如果只想選擇它,可以使用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 [] text in years列。

也請避免在關系名稱中使用保留字。 無論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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM