設置:
create table mapping(id int, group_name text);
insert into mapping
select i, format('Group%s', chr(i+ 64))
from generate_series(1, 15) i;
create table users (user_name text, user_ids int[]);
insert into users values
('User1', '{1,5,7}'),
('User2', '{2,5,9}'),
('User3', '{3,5,11,15}');
一步一步(理解查詢,看SqlFiddle):
使用UNNEST()列出所有單一的user_id在一排:
select user_name, unnest(user_ids) user_id
from users
通過加入映射來替換group_name中的user_id:
select user_name, group_name
from (
select user_name, unnest(user_ids) id
from users
) u
join mapping m on m.id = u.id
骨料組名成數組USER_NAME:
select user_name, array_agg(group_name)
from (
select user_name, group_name
from (
select user_name, unnest(user_ids) id
from users
) u
join mapping m on m.id = u.id
) m
group by 1
使用拷貝命令的最後一個查詢:
copy (
select user_name, array_agg(group_name)
from (
select user_name, group_name
from (
select user_name, unnest(user_ids) id
from users
) u
join mapping m on m.id = u.id
) m
group by 1
)
to 'c:/data/example.txt' (format csv)
@TimBiegeleisen:我覺得他寫一個CSV文件,該表顯示存儲在'integer []'列中的組ID(這很好,並且由PostgreSQL支持)。 –
是的,這就是我所做的! – Pravin