Re: Help me with this multi-table query

From: Dean Rasheed <dean(dot)a(dot)rasheed(at)googlemail(dot)com>
To: Nilesh Govindarajan <lists(at)itech7(dot)com>
Cc: pgsql-general General <pgsql-general(at)postgresql(dot)org>
Subject: Re: Help me with this multi-table query
Date: 2010-03-23 19:15:07
Message-ID: 8e2dbb701003231215n4ee2a917o1609ca6e4819ee13@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On 23 March 2010 11:07, Nilesh Govindarajan <lists(at)itech7(dot)com> wrote:
> Hi,
>
> I want to find out the userid, nodecount and comment count of the userid.
>
> I'm going wrong somewhere.
>
> Check my SQL Code-
>
> select u.uid, count(n.nid) nc , count(c.cid) cc from users u left join node
> n on ( n.uid = u.uid ) left join comments c on ( c.uid = u.uid ) group by
> u.uid having u.uid <> 0 order by u.uid;
>

I think you want select u.uid, count(distinct n.nid) nc ,
count(distinct c.cid) cc from ...
otherwise you're counting each node/comment multiple times as the rows in the
join multiply up (note 85 x 174 = 14790).

For big tables, this could start to become inefficient, and you might
be better off
doing your queries 1 and 2 above as sub-queries and joining them in an
outer query.

Regards,
Dean

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Craig Ringer 2010-03-24 04:13:57 Re: server-side extension in c++
Previous Message Tom Lane 2010-03-23 16:41:42 Re: Fwd: Before triggers and usage in partitioned tables