X-Original-To: pgsql-sql-postgresql.org@localhost.postgresql.org Received: from localhost (unknown [64.117.224.130]) by svr1.postgresql.org (Postfix) with ESMTP id DE2F2D1B8CC for ; Tue, 26 Aug 2003 00:48:04 -0300 (ADT) Received: from svr1.postgresql.org ([64.117.224.193]) by localhost (neptune.hub.org [64.117.224.130]) (amavisd-new, port 10024) with ESMTP id 51600-03 for ; Tue, 26 Aug 2003 00:47:34 -0300 (ADT) Received: from p15140235.pureserver.info (sql-info.de [217.160.166.164]) by svr1.postgresql.org (Postfix) with ESMTP id BD3FDD1B8D3 for ; Tue, 26 Aug 2003 00:47:33 -0300 (ADT) Received: from iwate.sql-info.de (pD9E0E107.dip.t-dialin.net [217.224.225.7]) (using SSLv3 with cipher RC4-MD5 (128/128 bits)) (No client certificate requested) by p15140235.pureserver.info (Postfix) with ESMTP id 4377FE41; Tue, 26 Aug 2003 05:47:31 +0200 (CEST) From: Ian Barwick To: Joseph Shraibman , pgsql-sql@postgresql.org Subject: Re: How to join from two tables at once? Date: Tue, 26 Aug 2003 05:46:19 +0200 User-Agent: KMail/1.5.1 References: In-Reply-To: MIME-Version: 1.0 Content-Type: text/plain; charset="iso-8859-1" Content-Transfer-Encoding: 7bit Content-Disposition: inline Message-Id: <200308260546.20084.barwick@gmx.net> X-Virus-Scanned: by amavisd-new at postgresql.org X-Archive-Number: 200308/297 X-Sequence-Number: 14913 On Tuesday 26 August 2003 02:58, Joseph Shraibman wrote: > How can I join on one table with join conditions refering to two tables? > In this example p is missing an entry that corresponds to u. I want to > select from u and p, but have entries in u that don't have an entry in p. > The problem is I need to go through table a to get the corresponding value > in table p, and a LEFT JOIN only operates on two tables. The subselect > works, but in real life turns out to be a big performance drain. (...) > -- doesn't get 2, because there is no entry in p for it > SELECT u.uid, u.txt, p.val FROM u,a,p WHERE u.uid = p.uid and a.id = u.aid > and p.pkey = a.pkey; > > -- works, but uses a subselect > SELECT u.uid, u.txt, (SELECT p.val FROM p WHERE p.uid = u.uid AND p.pkey = > a.pkey) FROM u,a WHERE a.id = u.aid; > > --doesn't work: ERROR: JOIN/ON clause refers to "u", which is not part of > JOIN SELECT u.uid, u.txt, p.val FROM u,a LEFT JOIN p ON p.uid = u.uid AND > p.pkey = a.pkey WHERE a.id = u.aid; Try: SELECT u.uid, u.txt, p.val FROM u INNER JOIN a ON (a.id=u.aid) LEFT JOIN p ON (p.pkey=a.pkey AND p.uid=u.uid) Ian Barwick barwick@gmx.net