pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Doug Younger <postgres@mindspring.com>
Cc: pgsql-sql@postgreSQL.org
Subject: Re: [SQL] Problems using count() with a join
Date: Thu, 19 Aug 1999 09:16:30 -0400
Message-ID: <7784.935068590@sss.pgh.pa.us> (raw)
In-Reply-To: <4.2.0.58.19990818215523.00c808b0@proxy>

Doug Younger <postgres@mindspring.com> writes:
> What I want is to get a count of # of users in each group, even if there 
> are no users in the group.

> I have tried the following:
> SELECT t1.g_name,count(t2.g_id)
>    FROM groups t1,users t2
>    WHERE t1.g_id = t2.g_id
>    GROUP BY t1.g_name;

> But it only give the counts of users in each group if there actually are 
> users in that group.
> I want the count to be 0 if there are no users in the group.

Try SELECT as above plus

... UNION
    SELECT t1.g_name, 0
    FROM groups t1
    WHERE NOT EXISTS(SELECT * FROM users t2 WHERE t1.g_id = t2.g_id);

Grotty, I know, but we don't have outer joins yet...

			regards, tom lane



view thread (2+ messages)

Message-ID: <7784.935068590@sss.pgh.pa.us>
Permalink:  ../7784.935068590@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/7784.935068590@sss.pgh.pa.us

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-sql@postgresql.org
  Cc: tgl@sss.pgh.pa.us, postgres@mindspring.com
  Subject: Re: [SQL] Problems using count() with a join
  In-Reply-To: <7784.935068590@sss.pgh.pa.us>
  References: <4.2.0.58.19990818215523.00c808b0@proxy> <7784.935068590@sss.pgh.pa.us>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox