Received: from localhost (maia-4.hub.org [200.46.204.183]) by postgresql.org (Postfix) with ESMTP id B446E9FBB4E for ; Wed, 14 Mar 2007 15:01:32 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.183]) (amavisd-new, port 10024) with ESMTP id 54602-02-2 for ; Wed, 14 Mar 2007 15:01:22 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey-1.7.4 Received: from smtp1.execulink.net (smtp1.execulink.net [69.63.44.82]) by postgresql.org (Postfix) with ESMTP id 4F9779FBB4D for ; Wed, 14 Mar 2007 15:01:22 -0300 (ADT) Received: from acer.sympatico.ca (node-6114.tor.pppoe.execulink.com [67.158.71.227]) by smtp1.execulink.net (8.13.1/8.12.11) with ESMTP id l2EIBbqc012858 for ; Wed, 14 Mar 2007 14:11:39 -0400 Message-Id: <5.2.1.1.0.20070314133826.050002b0@pop6.sympatico.ca> X-Sender: b1wudu74@pop6.sympatico.ca X-Mailer: QUALCOMM Windows Eudora Version 5.2.1 Date: Wed, 14 Mar 2007 13:58:01 -0400 To: pgsql-sql@postgresql.org From: Frank Bax Subject: Re: Joins on many-to-many relations. In-Reply-To: Mime-Version: 1.0 Content-Type: text/plain; charset="us-ascii"; format=flowed X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0.988 tagged_above=0 required=5 tests=AWL, BAYES_50, FORGED_RCVD_HELO, SPF_NEUTRAL X-Spam-Level: X-Archive-Number: 200703/202 X-Sequence-Number: 27840 At 11:39 AM 3/14/07, Wiebe Cazemier wrote: >Consider this scenario of three (simplified) tables: > >people >- id >- name > >accounts >- id >- owner_id REFERENCES people > >account_co_owners >- co_owner_id REFERENCES people >- account_id REFERENCES accounts > >I need a query that allows the user to search for accounts by giving names of >either co-owners or owners. Currently, the query responsible is this: > >SELECT DISTINCT ON (account.id) account.* >FROM accounts AS account >INNER JOIN people AS owner > ON owner.id = account.owner_id > OR owner.id IN (SELECT co_owner_id > FROM account_co_owners > WHERE account_id = account.id > AND co_owner_id = owner.id) >WHERE owner.name LIKE '%user supplied search string%'; > >But this query is too slow for my taste. A performance question should always include the output of EXPLAIN ANALYZE. I think the problem is database design. If you added a boolean column into accounts table which would indicate owner/co-owner; then all data from account_co_owner could be merged into accounts and the query would be much simpler to code. I don't expect this code to be any quicker; but I think it more clearly identifies the problem with your design: SELECT accounts.* from accounts inner join ( SELECT account.* FROM ( select id,owner_id from accounts union select account_id,co_owner_id from account_co_owners ) as account INNER JOIN ( SELECT id FROM people WHERE name LIKE '%user%' ) AS owner on account.owner_id = owner.id ) as acct on acct.id=accounts.id;