Re: joining a query with a select count(*)

From: John Sidney-Woollett <johnsw(at)wardbrook(dot)com>
To:
Cc: PostgreSQL general <pgsql-general(at)postgresql(dot)org>
Subject: Re: joining a query with a select count(*)
Date: 2005-11-05 19:31:14
Message-ID: 436D0882.2080506@wardbrook.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

I think that something like this should work for you

SELECT child_pk, coalesce(cnt, 0)
FROM childtable c
left outer join (
SELECT child_fk, count(*) as cnt
FROM grandchildtable
GROUP BY child_fk
) t
ON (c.child_pk= t.child_fk);

IMHO, if Postgres had Oracle's (+) notation these would be a lot easier...

John

Matthew Terenzio wrote:
>
> I want a query to return all the rows from one table along with a count
> of rows in another table that reference each returned row from the first
> table.
>
> For instance, if you had a table of children and another table of
> grandchildren that had a foreign key on the children table, I'd want to
> return all children with a count of the number of kids they had.
>
> I hope I can figure it out before I get a reply.
>
> Thanks
>
>
> ---------------------------(end of broadcast)---------------------------
> TIP 4: Have you searched our list archives?
>
> http://archives.postgresql.org

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Florian G. Pflug 2005-11-05 20:28:19 Re: [GENERAL] Missing variable "role" in "pg_settings"?
Previous Message Berend Tober 2005-11-05 19:09:40 Re: Duplicate Row Removal