X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.144]) by svr1.postgresql.org (Postfix) with ESMTP id 092BE3A3C47 for ; Tue, 16 Nov 2004 13:25:59 +0000 (GMT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (av.hub.org [200.46.204.144]) (amavisd-new, port 10024) with ESMTP id 17846-08 for ; Tue, 16 Nov 2004 13:25:46 +0000 (GMT) Received: from tht.net (vista.tht.net [216.126.88.2]) by svr1.postgresql.org (Postfix) with ESMTP id 89F5A3A3C24 for ; Tue, 16 Nov 2004 13:25:48 +0000 (GMT) Received: from dyn-69-135.tor.dsl.tht.net (dyn-69-135.tor.dsl.tht.net [134.22.69.135]) by tht.net (Postfix) with ESMTP id DC0F976A4D; Tue, 16 Nov 2004 08:25:47 -0500 (EST) Subject: Re: tree structure photo gallery date quiery From: Rod Taylor To: Gary Stainburn Cc: pgsql-sql@postgresql.org In-Reply-To: <200411161129.46131.gary.stainburn@ringways.co.uk> References: <200411161129.46131.gary.stainburn@ringways.co.uk> Content-Type: text/plain Date: Tue, 16 Nov 2004 08:23:23 -0500 Message-Id: <1100611403.99341.21.camel@home> Mime-Version: 1.0 X-Mailer: Evolution 2.0.2 FreeBSD GNOME Team Port Content-Transfer-Encoding: 7bit X-Virus-Scanned: by amavisd-new at hub.org X-Spam-Status: No, hits=0.0 tagged_above=0.0 required=5.0 tests= X-Spam-Level: X-Archive-Number: 200411/144 X-Sequence-Number: 19463 On Tue, 2004-11-16 at 11:29 +0000, Gary Stainburn wrote: > > How would I go about creating a view to show a) the number of photos > in > a gallery and b) the timestamp of the most recent addition for a > gallery, so that it interrogates all sub-galleries? There isn't a very simple answer to that question because you don't have enough information. To make that view, you require there to be a maximum depth to the galleries (say 3 galleries deep only -- including root) OR you need another structure which represents the relationship between all of the galleries. For the latter, something like gallery_lookup(id, cid, nest_depth): 1 1 0 2 2 0 3 3 0 4 4 0 5 5 0 6 6 0 7 7 0 1 2 1 1 3 1 1 4 2 1 5 2 1 6 2 1 7 2 2 4 1 2 5 1 2 6 1 3 7 1 Now that you know the relationship between them all, you can quickly and easily determine all galleries underneath the top level one. Sorry, don't know the technical term, if there is one, for this operation. Now lets make a pair of views: CREATE VIEW gallery_aggregate AS SELECT id, name, sum(CASE WHEN pid IS NULL THEN 0 ELSE 1 END) AS photocount, max(added) AS max_added FROM gallery LEFT OUTER JOIN photos USING (id) GROUP BY id, name; CREATE VIEW gallery_view_you_want AS SELECT name, sum(photocount), max(max_added) FROM gallery JOIN gallery_lookup AS gl USING (id) JOIN gallery_aggregate AS ga ON (gl.cid = ga.id) GROUP BY name; There are plenty of steps you can take to make this both faster and/or use less storage; optimize aggregates, use a function to calculate the 'gallery_lookup' contents, etc. None of this has been tested. --