Re: subquery/alias question

From: Alvaro Herrera <alvherre(at)commandprompt(dot)com>
To: Michael Glaesemann <grzm(at)seespotcode(dot)net>
Cc: Madison Kelly <linux(at)alteeve(dot)com>, PostgreSQL General <pgsql-general(at)postgresql(dot)org>
Subject: Re: subquery/alias question
Date: 2007-09-25 22:30:48
Message-ID: 20070925223048.GN6440@alvh.no-ip.org
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Michael Glaesemann wrote:
>
> On Sep 25, 2007, at 16:59 , Madison Kelly wrote:
>
>> SELECT
>> d.dom_id,
>> d.dom_name,
>> (SELECT COUNT(*) FROM users u WHERE u.usr_dom_id=d.dom_id)
>> AS
>> usr_count
>> FROM
>> domains d
>> WHERE
>> (SELECT COUNT(*) FROM users u WHERE u.usr_dom_id=d.dom_id) > 0
>> ORDER BY d.dom_name ASC;
>
> Why not just use a join? Something like this would work, I should think:
>
> select dom_id,
> dom_name,
> usr_count
> from domains
> natural join (select usr_dom_id as dom_id,
> count(usr_dom_id) as usr_count
> from users) u
> where usr_count > 0
> order by dom_name;

Maybe the usr_count should be tested in a HAVING clause instead of
WHERE? And put the count(*) in the result list instead of a subselect.
That feels more natural to me anyway.

--
Alvaro Herrera http://www.CommandPrompt.com/
The PostgreSQL Company - Command Prompt, Inc.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message paul.dorman 2007-09-26 02:03:17 DAGs and recursive queries
Previous Message Greg Smith 2007-09-25 22:21:10 Re: lowering impact of checkpoints