how to write an optimized sql with two same subsql?

From: sunpeng <bluevaley(at)gmail(dot)com>
To: pgsql-general(at)postgresql(dot)org
Subject: how to write an optimized sql with two same subsql?
Date: 2010-10-14 23:34:10
Message-ID: AANLkTin6fUFO3mO-AMEX=-xWQV16gOzmyWcRdBWL+SSw@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

We have a table A:
CREATE TABLE A(
uid integer,
groupid integer
)
Now we use this subsql to get each group's count:
SELECT count(*) as count
FROM A
GROUP BY groupid
ORDER BY groupid

Then we try to find the group pair with following conditions:
SELECT c.groupid as groupid1,d.groupid as groupid2
FROM subsql as c, subsql as d
WHERE d.groupid > c.groupid
and d.count > c.count;

Does that mean subsql will be executed twice? or how to write the optimized
sql?

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Nick 2010-10-14 23:49:07 It it possible to get this result in one query?
Previous Message John R Pierce 2010-10-14 22:55:47 Re: how to get current sql execution time?