聽起來像是array_agg
給我一份工作。隨着表是這樣的:
create table t (id int not null, title varchar not null);
create table g (id int not null, name varchar not null);
create table tg (t int not null, g int not null);
你可以做這樣的事情:
SELECT t.title, array_agg(g.name)
FROM t, tg, g
WHERE t.id = tg.t
AND tg.g = g.id
GROUP BY t.title, t.id
獲得:
title | array_agg
-------+-----------------------
one | {g-one,g-two,g-three}
three | {g-three}
two | {g-two}
然後,只需解壓陣列需要。如果由於某種原因,你真的想要一個逗號分隔的字符串,而不是一個數組,那麼string_agg
是你的朋友:
SELECT t.title, string_agg(g.name, ',')
FROM t, tg, g
WHERE t.id = tg.t
AND tg.g = g.id
GROUP BY t.title, t.id
,你會得到這樣的事情:
title | string_agg
-------+---------------------
one | g-one,g-two,g-three
three | g-three
two | g-two
我會去數組方法,這樣您就不必擔心爲分隔符保留一個字符,或者在聚合時必須轉義(然後忽略)分隔符。
這很好。謝謝! – csano 2011-03-09 07:09:12