Received: from localhost (unknown [200.46.204.184]) by postgresql.org (Postfix) with ESMTP id C911B2E0037 for ; Mon, 10 Dec 2007 00:45:58 -0400 (AST) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.184]) (amavisd-maia, port 10024) with ESMTP id 79096-06 for ; Mon, 10 Dec 2007 00:45:54 -0400 (AST) Received: from ipmail01.adl6.internode.on.net (ipmail01.adl6.internode.on.net [203.16.214.146]) by postgresql.org (Postfix) with ESMTP id 3809B2E0033 for ; Mon, 10 Dec 2007 00:45:53 -0400 (AST) X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: Aq4HAENTXEfLevdH/2dsb2JhbACBWg X-IronPort-AV: E=Sophos;i="4.23,274,1194183000"; d="scan'208";a="3319580" Received: from ppp247-71.static.internode.on.net (HELO DevBox.local) ([203.122.247.71]) by ipmail01.adl6.internode.on.net with ESMTP; 10 Dec 2007 15:15:46 +1030 Message-ID: <475CC478.7010102@Sheeky.Biz> Date: Mon, 10 Dec 2007 15:15:44 +1030 From: Shane Ambler User-Agent: Thunderbird 2.0.0.6 (Macintosh/20070728) MIME-Version: 1.0 To: Gerry Reno CC: pgsql-sql@postgresql.org Subject: Re: join on three tables is slow References: <475C96EA.6090002@verizon.net> In-Reply-To: <475C96EA.6090002@verizon.net> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200712/29 X-Sequence-Number: 29721 Gerry Reno wrote: > I have a join that uses three tables but it runs rather slow. For > example, the following command takes about 10 min. to run. It gets the > correct result but what should I do to increase the performance of this > query? This query is the end result of some python code hence the big > id list. > > myfile has 600 records, res_partner has 600 records, res_partner_address > has 1000 records > > select p.addr, p.name, p.name2 from myfile as p join res_partner as e on > e.id in ( 3214, 3213, 3212, 3211, 3210, 3209, 3208, 3207, 3206, 3205, snip > 3179, 3178, 3177, 50, 49, 48, 47, 22, 25 ) join res_partner_address as a > on a.partner_id = e.id and (a.type = 'default' or a.type IS NULL) and > (p.name != a.name or p.name2 != a.name2) and p.addr = e.addr where > e.active = '1' and p.date = e.date and e.date = (select max(date) from > res_partner as msd where msd.addr = p.addr) > To start with - You have join res_partner as e on e.id in (... big list...) That list should be the contents of a where clause not a join. You want that first part to be join res_partner as e on e.id=p.something So as a first step that join will link all 523 res_partner rows listed with every myfile row - that means you will get 313,800 rows from this join with your other joins and where clause then trim that down to the final result. I would also say that the rest of your joins don't appear to be what you really want. (but part of them may belong in the where clause) -- Shane Ambler pgSQL (at) Sheeky (dot) Biz Get Sheeky @ http://Sheeky.Biz