X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [200.46.204.2]) by svr1.postgresql.org (Postfix) with ESMTP id B6031D1D08A for ; Wed, 7 Apr 2004 07:10:12 -0300 (ADT) Received: from svr1.postgresql.org ([200.46.204.71]) by localhost (neptune.hub.org [200.46.204.2]) (amavisd-new, port 10024) with ESMTP id 13346-10 for ; Wed, 7 Apr 2004 07:10:13 -0300 (ADT) Received: from news.hub.org (news.hub.org [200.46.204.72]) by svr1.postgresql.org (Postfix) with ESMTP id E6CB7D1D085 for ; Wed, 7 Apr 2004 07:10:10 -0300 (ADT) Received: from news.hub.org (news.hub.org [200.46.204.72]) by news.hub.org (8.12.9/8.12.9) with ESMTP id i37AAASx028261 for ; Wed, 7 Apr 2004 10:10:10 GMT (envelope-from news@news.hub.org) Received: (from news@localhost) by news.hub.org (8.12.9/8.12.9/Submit) id i37A6jcY027722 for pgsql-sql@postgresql.org; Wed, 7 Apr 2004 10:06:45 GMT Message-Id: <1928683.cthc5y6rJJ@weyoun.foo.at> From: Stefan Weiss Subject: Counting rows from two tables in one query X-Newsgroups: comp.databases.postgresql.sql Lines: 42 Organization: Foo Orbital Operations User-Agent: KNode/0.7.1 MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7Bit Date: Wed, 07 Apr 2004 10:06:20 GMT X-Complaints-To: abuse@news.chello.at To: pgsql-sql@postgresql.org X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200404/80 X-Sequence-Number: 17455 Hi. I have a (simplified) table layout like this: +---------+ +---------+ | sub_a | +------+ | sub_b | +---------+ | main | +---------+ | id | +------+ | id | | main_id | ----> | id | <---- | main_id | | ... | | ... | | ... | +---------+ +------+ +---------+ What I am trying to get is a list that shows how many records from 'sub_a' and 'sub_b' are referencing 'main': main_id | count_a | count_b ---------+---------+--------- 1 | 2 | 1 2 | 12 | 1 3 | 7 | 3 [......] This query obviously does not do what I need, it gives me the product of count_a and count_b in both columns instead: select main.id as main_id, count(sub_a.*) as count_a, count(sub_b.*) as count_b from main, sub_a, sub_b where sub_a.main_id = main.id and sub_b.main_id = main.id group by main.id having count(sub_a.*) > 0 and count(sub_b.*) > 0 ; Is it possible to get a list like the one above with a single query? thanks, stefan