Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 6B972475DAD for ; Thu, 31 Oct 2002 15:37:54 -0500 (EST) Received: from beamish.nsd.ca (unknown [205.150.156.194]) by postgresql.org (Postfix) with ESMTP id A52D2475BC3 for ; Thu, 31 Oct 2002 15:37:53 -0500 (EST) Received: (from smap@localhost) by beamish.nsd.ca (8.9.3/8.9.3) id PAA13607; Thu, 31 Oct 2002 15:37:41 -0500 X-Authentication-Warning: beamish.nsd.ca: smap set sender to using -f Received: from reddog.nsd.ca(192.168.101.30) by beamish.nsd.ca via smap (V2.1/2.1+anti-relay+anti-spam) id xma013603; Thu, 31 Oct 02 15:37:41 -0500 Received: from nsd.ca (jllachan-linux.nsd.ca [192.168.101.148]) by reddog.nsd.ca (8.8.7/8.8.7) with ESMTP id PAA27914; Thu, 31 Oct 2002 15:36:59 -0500 Message-ID: <3DC194BC.966E95CD@nsd.ca> Date: Thu, 31 Oct 2002 15:38:20 -0500 From: Jean-Luc Lachance X-Mailer: Mozilla 4.77 [en] (X11; U; Linux 2.4.9-31 i686) X-Accept-Language: en MIME-Version: 1.0 To: Richard Huxton Cc: Wei Weng , pgsql-sql@postgresql.org Subject: Re: How do you write this query? References: <1036088486.13986.19.camel@Monet> <200210311909.11341.dev@archonet.com> Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Virus-Scanned: by AMaViS new-20020517 X-Archive-Number: 200210/425 X-Sequence-Number: 10142 Thank goodness for nested select! select data1 from test where data2 = ( select distinct data2 from test where data1 = 'pooh') and data = 3; JLL Richard Huxton wrote: > > On Thursday 31 Oct 2002 6:21 pm, Wei Weng wrote: > > data | data1 | data2 > > ------+-------+------- > > 1 | foo | bar > > 2 | greg | bar > > 3 | pooh | bar > > 4 | dah | peng > > > > I need a query that returns me the "data1" that satisfies the logic of > > the following pseudo code: > > > > 1: select data2 into @out from test where data1 = 'pooh' > > 2: select data1 from test where data2 = @out and data = 3 > > The most literal would be something like: > > SELECT t1.data1 FROM test t1 > WHERE t1.data=3 AND t1.data2 IN > (SELECT t2.data2 > FROM test t2 > WHERE t2.data1='pooh') > > You can probably get away without the t1/t2 stuff but that should make things > clear. > > Since Postgresql isn't very good at optimising IN, you might want to rewrite > it as an EXISTS query instead - see the manuals and mailing list archives for > details. > > HTH > -- > Richard Huxton > > ---------------------------(end of broadcast)--------------------------- > TIP 5: Have you checked our extensive FAQ? > > http://www.postgresql.org/users-lounge/docs/faq.html