Re: Additional select fields in a GROUP BY - Mailing list pgsql-performance

From Bruno Wolff III
Subject Re: Additional select fields in a GROUP BY
Date
Msg-id 20040613135212.GA3260@wolff.to
Whole thread Raw
In response to Additional select fields in a GROUP BY  (Vitaly Belman <vitalib@012.net.il>)
Responses Re: Additional select fields in a GROUP BY  (Vitaly Belman <vitalyb@gmail.com>)
List pgsql-performance
On Sun, Jun 13, 2004 at 06:21:17 +0300,
  Vitaly Belman <vitalib@012.net.il> wrote:
>
> Consider the following query:
>
> select t1field1, avg(t2fieild2)
> from t1, t2
> where t1.field1 = t2.field2
> group by t1field1
>
> That works fine. But I'd really like to see more fields of t1 in this
> query, however I can't add them into the select because they're not
> part of the GROUP BY, thus I have to add them to there too:

If t1.field1 is a candiate key for t1, then the normal thing to do is
to group t2 by t2.field1 (assuming you really meant to join on t2.field1,
not t2.field2) and THEN join to t1. That may even be faster than the way you
are doing things now.

So the query would look like:

SELECT t1.field1, t1.field2, t1.field3, a.t2avg FROM t1,
  (SELECT field1, avg(field2) as t2avg FROM t2 GROUP BY field1) as a
  WHERE t1.field1 = a.field1

pgsql-performance by date:

Previous
From: Tom Lane
Date:
Subject: Re: Additional select fields in a GROUP BY
Next
From: Vitaly Belman
Date:
Subject: Re: Additional select fields in a GROUP BY