やりたいこと
select した結果のレコードのフィールドを連結した文字列を取得する。
例えば、select の結果が id = 1, 2, 3 のレコードの場合、"1, 2, 3" の文字列を取得する。
select の結果を文字列として連結
テーブル定義例
create table test1 (
id integer generated always as identity primary key,
name varchar(32) not null
);
insert into test1 (name) values ('aaa');
insert into test1 (name) values ('bbb');
insert into test1 (name) values ('ccc');
string_agg()
string_agg({フィールド}, {セパレータ}) で select の結果を文字列として連結することができる。
# select string_agg(id::text, ', ' order by id asc) from test1;
string_agg
------------
1, 2, 3
(1 row)
同一レコードの複数のフィールドを連結したい場合には、concat() でフィールド単位で連結した結果を、レコード毎に連結することができる。
# select string_agg(concat(id::text, ':', name), ', ' order by id asc) from test1;
string_agg
---------------------
1:aaa, 2:bbb, 3:ccc
(1 row)
フィールド毎に string_agg() で連結することもできる。
# select
string_agg(id::text, ', ' order by id asc),
string_agg(name, ', ' order by id asc)
from test1;
string_agg | string_agg
------------+---------------
1, 2, 3 | aaa, bbb, ccc
(1 row)