Received: from localhost (maia-5.hub.org [200.46.204.182]) by postgresql.org (Postfix) with ESMTP id 47A909FB9D8 for ; Wed, 14 Mar 2007 12:40:19 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.204.182]) (amavisd-new, port 10024) with ESMTP id 74429-05-3 for ; Wed, 14 Mar 2007 12:40:10 -0300 (ADT) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.4 Received: from ciao.gmane.org (main.gmane.org [80.91.229.2]) by postgresql.org (Postfix) with ESMTP id C54DF9FB9C6 for ; Wed, 14 Mar 2007 12:40:11 -0300 (ADT) Received: from list by ciao.gmane.org with local (Exim 4.43) id 1HRVa1-0003Sd-MI for pgsql-sql@postgresql.org; Wed, 14 Mar 2007 16:39:57 +0100 Received: from cc503261-a.eelde1.dr.home.nl ([212.204.130.190]) by main.gmane.org with esmtp (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Wed, 14 Mar 2007 16:39:57 +0100 Received: from halfgaar by cc503261-a.eelde1.dr.home.nl with local (Gmexim 0.1 (Debian)) id 1AlnuQ-0007hv-00 for ; Wed, 14 Mar 2007 16:39:57 +0100 X-Injected-Via-Gmane: http://gmane.org/ To: pgsql-sql@postgresql.org From: Wiebe Cazemier Subject: Joins on many-to-many relations. Date: Wed, 14 Mar 2007 16:39:42 +0100 Lines: 42 Message-ID: Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7Bit X-Complaints-To: usenet@sea.gmane.org X-Gmane-NNTP-Posting-Host: cc503261-a.eelde1.dr.home.nl User-Agent: KNode/0.10.4 X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200703/197 X-Sequence-Number: 27835 Hi, Doing a join on one-to-many relations (like "orders" joining "custumors") is easy, but what if there are many-to-many relations involved? 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. It takes about 3 seconds, for only 800 accounts). Without the subselect in the JOIN statement (and therefor without the ability to search based on the co-owner names), it is significantly faster. My question is, can joining many-to-many relations be done in a better way than what I'm doing here? Thanks in advance.