Queries for PostgreSQL 8.3 that do not have window functions.
With large tables, it is often much faster to use a JOIN instead of a correlated subquery .
The first query aggregates the values ββfor Table2 before joining Table1 , which should also be faster:
SELECT t1.id, t2.aid, t1.name, t2.data, COALESCE(t2.ct, 1) AS number FROM Table1 t1 LEFT JOIN ( SELECT x.aid, x.data, count(y.aid) + 1 AS ct FROM Table2 x LEFT JOIN Table2 y ON x.aid = y.aid AND x.id > y.id GROUP BY x.aid, x.data ) t2 ON t2.aid = t1.id ORDER BY t1.id, t2.ct;
And ORDER BY needs to be fixed.
Alternative without subquery. Perhaps it will be faster:
SELECT t1.id, t2.aid, t1.name, t2.data, count(*) + count(t3.id) AS number FROM Table1 t1 LEFT JOIN Table2 t2 ON t2.aid = t1.id LEFT JOIN Table2 t3 ON t3.aid = t2.aid AND t3.id < t2.id GROUP BY t1.id, t2.aid, t1.name, t2.data ORDER BY t1.id, count(t3.id);
Not sure, not tested with a large set. Check performance with EXPLAIN ANALYZE . Could you report your results?
source share