Agregue funções em várias tabelas unidas
Eu tenho três tabelas:
CREATE TABLE foo (
id bigint PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE foo_bar (
id bigint PRIMARY KEY,
foo_id bigint NOT NULL
);
CREATE TABLE tag (
name text NOT NULL,
target_id bigint NOT NULL,
PRIMARY KEY (name, target_id)
);
Eu estou tentando criar uma visão tal que eu recebo todos os campos da tabelafoo
, a contagem de itens emfoo_bar
Ondefoo.id = foo_bar.foo_id
e uma matriz de texto de todas as tags ondefoo.id = tag.target_id
. Se tiver-mos:
INSERT INTO foo VALUES (1, 'one');
INSERT INTO foo VALUES (2, 'two');
INSERT INTO foo_bar VALUES (1, 1);
INSERT INTO foo_bar VALUES (2, 1);
INSERT INTO foo_bar VALUES (3, 2);
INSERT INTO foo_bar VALUES (4, 1);
INSERT INTO foo_bar VALUES (5, 2);
INSERT INTO tag VALUES ('a', 1);
INSERT INTO tag VALUES ('b', 1);
INSERT INTO tag VALUES ('c', 2);
O resultado deve retornar:
foo.id | foo.name | count | array_agg
--------------------------------------------------
1 | one | 3 | {a, b}
2 | two | 2 | {c}
Isto é o que eu tenho até agora:
SELECT DISTINCT f.id, f.name, COUNT(b.id), array_agg(t.name)
FROM foo AS f, foo_bar AS b, tag AS t
WHERE f.id = t.target_id AND f.id = b.foo_id
GROUP BY f.id, b.id;
Estes são os resultados que estou obtendo (observecount
está incorreto):
foo.id | foo.name | count | array_agg
--------------------------------------------------
1 | one | 2 | {a, b}
2 | two | 1 | {c}
ocount
é sempre a contagem de tags em vez da contagem de distintasfoo_bar
valores. Eu tentei reordenar / modificar oGROUP BY
e aSELECT
cláusulas que retornam resultados diferentes, mas não as que estou procurando. Eu acho que estou tendo problemas com oarray_agg()
função, mas não tenho certeza se esse é o caso ou como resolvê-lo.