Received: from localhost (maia-3.hub.org [200.46.204.184]) by postgresql.org (Postfix) with ESMTP id 794299F97DA for ; Tue, 21 Aug 2007 16:16:54 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.184]) (amavisd-maia, port 10024) with ESMTP id 47250-01 for ; Tue, 21 Aug 2007 16:16:41 -0300 (ADT) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.5 Received: from web31805.mail.mud.yahoo.com (web31805.mail.mud.yahoo.com [68.142.207.68]) by postgresql.org (Postfix) with SMTP id 463D29F97ED for ; Tue, 21 Aug 2007 16:16:44 -0300 (ADT) Received: (qmail 2171 invoked by uid 60001); 21 Aug 2007 19:16:41 -0000 DomainKey-Signature: a=rsa-sha1; q=dns; c=nofws; s=s1024; d=yahoo.com; h=X-YMail-OSG:Received:Date:From:Subject:To:In-Reply-To:MIME-Version:Content-Type:Content-Transfer-Encoding:Message-ID; b=BkqhL7KwsPvlyj7LgrnKKdhpcWdwVD9D/cdsXOT77r6/+EhYg6F5kvitdJwq1JLPKeMfwRgIxjXaULfZKZ6Ur2SPU78OYA4Za82k4GdGgvURQpVv1EfV6ZQDl3YWP8Ni82TUUFOPHBdXU/oMR5YSXP2H5hwsdtkTGwsu5cdNELk=; X-YMail-OSG: 3Ye9G20VM1mYW0Io371UqZrh7YOVolWKxumoYYTujCeIOsEl96MCLcE1FWUXKMlzUzC602wFCQ-- Received: from [12.180.237.138] by web31805.mail.mud.yahoo.com via HTTP; Tue, 21 Aug 2007 12:16:40 PDT Date: Tue, 21 Aug 2007 12:16:40 -0700 (PDT) From: Richard Broersma Jr Subject: Re: Join question To: tyrrill_ed@emc.com, pgsql-sql@postgresql.org In-Reply-To: <5C7C0B0734F87445AFC8B63EDCC4901E015ED7EE@CORPUSMX60C.corp.emc.com> MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: 8bit Message-ID: <73073.2010.qm@web31805.mail.mud.yahoo.com> X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200708/169 X-Sequence-Number: 29107 --- tyrrill_ed@emc.com wrote: > create table c ( > a_id int, > b_id int > ); > > I am doing a query like this: > > SELECT a.x, max(b.x) FROM a, b, c WHERE a.a_id = c.a_id AND b.b_id = > c.b_id GROUP by a.x; > > I only need to get one row from b for each row in a, and it really > doesn't matter which one. I use max() to get a single value from table > b. There are generally be dozens to hundreds of rows in b for each row > in a. The problem is when I have a query with tens of thousands of rows > in a that the join with b will have millions of rows, and is really > slow. The group by effectively reduces the results down to what I want, > but it still has to process the millions of rows. Does anyone know a > way I could restructure this query to get only one b for each a in a > faster way? CREATE INDEX table_c_foreign_key ON c ( a, b ); SELECT a.x, b.x FROM ( SELECT DISTINCT( a_id ) a_id, b_id FROM c ) AS c( a_id, b_id ) INNER JOIN a ON c.a_id = a.id INNER JOIN b ON c.b_id = b.id; Regards, Richard Broersma Jr.