Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id C50DF476D4C for ; Thu, 5 Dec 2002 15:08:11 -0500 (EST) Received: from ece.rice.edu (ece.rice.edu [128.42.4.34]) by postgresql.org (Postfix) with ESMTP id B0724476D60 for ; Thu, 5 Dec 2002 14:38:49 -0500 (EST) Received: from localhost (localhost [127.0.0.1]) by ece.rice.edu (Postfix) with SMTP id A039E68ABB; Thu, 5 Dec 2002 13:38:49 -0600 (CST) Received: from localhost (localhost [127.0.0.1]) by ece.rice.edu (Postfix) with ESMTP id 458B568ABA; Thu, 5 Dec 2002 13:38:49 -0600 (CST) Received: from wallace.ece.rice.edu (wallace.ece.rice.edu [128.42.12.154]) by ece.rice.edu (Postfix) with ESMTP id 5590568A7B; Thu, 5 Dec 2002 13:38:48 -0600 (CST) Received: from reedstrm by wallace.ece.rice.edu with local (Exim 3.36 #1 (Debian)) id 18K1pf-0005e9-00; Thu, 05 Dec 2002 13:38:47 -0600 Date: Thu, 5 Dec 2002 13:38:47 -0600 From: "Ross J. Reedstrom" To: Gary Stainburn Cc: pgsql-sql@postgresql.org Subject: Re: master-detail relationship and count Message-ID: <20021205193847.GA20976@wallace.ece.rice.edu> Mail-Followup-To: "Ross J. Reedstrom" , Gary Stainburn , pgsql-sql@postgresql.org References: <200211291439.50595.gary.stainburn@ringways.co.uk> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <200211291439.50595.gary.stainburn@ringways.co.uk> User-Agent: Mutt/1.4i X-Virus-Scanned: by AMaViS snapshot-20020300 X-DCC--Metrics: ece.rice.edu 1067; Body=1 Fuz1=1 Fuz2=1 X-Virus-Scanned: by AMaViS new-20020517 X-Archive-Number: 200212/68 X-Sequence-Number: 10656 On Fri, Nov 29, 2002 at 02:39:50PM +0000, Gary Stainburn wrote: > I've worked out a way of doing it by vreating a view for the tally info as: > > create view link_tally as > select lklid, lktype, count(*) from links group by lklid, lktype; > > and then doing: > > select r.rtid, r.rtname, l.count from route r > left outer join link_tally l on r.rtid = l.lklid and l.lktype = 'R'; > > (this works apart from the coalesce bit which I haven't worked out where to > put yet, and for the moment isn't important as NULL is okay as a result). > > However, I still can't get it to work straight from the tables. The nearest > I'ev got is: > > select r.rtid, r.rtname, subsel.cnt from route r, > (select r2.rtid as rid, count(lnk.lkid) as cnt from route r2, links lnk > where lnk.lktype='R' and lnk.lklid = r2.rtid group by r2.rtid) as subsel > left outer join subsel on r.rtid = subsel.rid; Hmm, I think this should work: select r.rtid, r.rtname, subsel.cnt from route r left outer join (select r2.rtid as rid, count(lnk.lklid) as cnt from route r2, links lnk where lnk.lktype='R' and lnk.lklid = r2.rtid group by r2.rtid) as subsel on r.rtid = subsel.rid; At least, it won't error. I don't have any test data to see if it returns what you want. Ross