X-Original-To: pgsql-general-postgresql.org@localhost.postgresql.org Received: from localhost (mx1.hub.org [200.46.208.251]) by postgresql.org (Postfix) with ESMTP id 14F859FA12E for ; Fri, 26 May 2006 14:21:20 -0300 (ADT) Received: from postgresql.org ([200.46.204.71]) by localhost (mx1.hub.org [200.46.208.251]) (amavisd-new, port 10024) with ESMTP id 76924-01 for ; Fri, 26 May 2006 14:21:14 -0300 (ADT) X-Greylist: from auto-whitelisted by SQLgrey- Received: from fetter.org (dsl092-188-065.sfo1.dsl.speakeasy.net [66.92.188.65]) by postgresql.org (Postfix) with ESMTP id 188699FA1F1 for ; Fri, 26 May 2006 14:21:14 -0300 (ADT) Received: by fetter.org (Postfix, from userid 500) id D4870C62BB; Fri, 26 May 2006 10:21:12 -0700 (PDT) Date: Fri, 26 May 2006 10:21:12 -0700 From: David Fetter To: John Taylor Cc: pgsql-general@postgresql.org Subject: Re: Syntax question Message-ID: <20060526172112.GE17861@fetter.org> References: <20060526160925.61343.qmail@web53504.mail.yahoo.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Disposition: inline In-Reply-To: <20060526160925.61343.qmail@web53504.mail.yahoo.com> User-Agent: Mutt/1.4.2.1i X-Virus-Scanned: Maia Mailguard 1.0.1 X-Archive-Number: 200605/1320 X-Sequence-Number: 96112 On Fri, May 26, 2006 at 09:09:25AM -0700, John Taylor wrote: > I have a select statement that goes as follows: > > SELECT * FROM product prod, prod_alias pa, category cat, company co > WHERE prod.catid = cat.catid > AND prod.coid = co.coid > AND prod.prodid = pa.prodid; > > If possible, I want to change the statement so that I get output > regardless of whether there's a match between prod.prodid and > pa.prodid. IOW, if there's a match between prod.prodid and > pa.prodid, I want the output from both the product table and the > prod_alias table. if there's no match, I still want the output > from product table. Can I do this in one select statement? Yes :) First, rewrite your query to make the JOINs explicit like this: /* Rewritten query #1 (Q1) */ SELECT prod.*, pa.*, cat.*, co.* -- *Slightly* better than * :P FROM product prod JOIN prod_alias pa ON (prod.prodid = pa.prodid) JOIN category cat ON (prod.catid = cat.catid) JOIN company co ON (prod.coid = co.coid) Then look up LEFT JOIN in the OUTER JOIN part of the manual others have pointed you to. What you'll come out with is something like this: /* Rewritten query #2 (Q2) */ SELECT prod.*, pa.*, cat.*, co.* -- *Slightly* better than * :P FROM product prod LEFT JOIN prod_alias pa ON (prod.prodid = pa.prodid) JOIN category cat ON (prod.catid = cat.catid) JOIN company co ON (prod.coid = co.coid) When you compart Q1 and Q2 side by side, you'll see that the only difference between Q1 and Q2 above is the word LEFT. HTH :) Cheers, D -- David Fetter http://fetter.org/ phone: +1 415 235 3778 AIM: dfetter666 Skype: davidfetter Remember to vote!