Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 240B94769F8 for ; Thu, 31 Oct 2002 14:15:04 -0500 (EST) Received: from anchor-post-34.mail.demon.net (anchor-post-34.mail.demon.net [194.217.242.92]) by postgresql.org (Postfix) with ESMTP id 6A9F74769EF for ; Thu, 31 Oct 2002 14:15:03 -0500 (EST) Received: from mwynhau.demon.co.uk ([193.237.186.96] helo=mainbox.archonet.com) by anchor-post-34.mail.demon.net with esmtp (Exim 3.35 #1) id 187KmS-000HDh-0Y; Thu, 31 Oct 2002 19:15:00 +0000 Received: from localhost (localhost.localdomain [127.0.0.1]) by mainbox.archonet.com (Postfix) with ESMTP id 700321599D; Thu, 31 Oct 2002 19:09:13 +0000 (GMT) Received: from client.archonet.com (client.archonet.com [192.168.1.16]) by mainbox.archonet.com (Postfix) with ESMTP id BE14615989; Thu, 31 Oct 2002 19:09:12 +0000 (GMT) Content-Type: text/plain; charset="utf-8" From: Richard Huxton Organization: Archonet Ltd To: Wei Weng , pgsql-sql@postgresql.org Subject: Re: How do you write this query? Date: Thu, 31 Oct 2002 19:09:11 +0000 User-Agent: KMail/1.4.3 References: <1036088486.13986.19.camel@Monet> In-Reply-To: <1036088486.13986.19.camel@Monet> MIME-Version: 1.0 Content-Transfer-Encoding: quoted-printable Message-Id: <200210311909.11341.dev@archonet.com> X-Virus-Scanned: by AMaViS snapshot-20020531 X-Virus-Scanned: by AMaViS new-20020517 X-Archive-Number: 200210/424 X-Sequence-Number: 10141 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 =3D 'pooh' > 2: select data1 from test where data2 =3D @out and data =3D 3 The most literal would be something like: SELECT t1.data1 FROM test t1 WHERE t1.data=3D3 AND t1.data2 IN (SELECT t2.data2=20 FROM test t2=20 WHERE t2.data1=3D'pooh') You can probably get away without the t1/t2 stuff but that should make thin= gs=20 clear. Since Postgresql isn't very good at optimising IN, you might want to rewrit= e=20 it as an EXISTS query instead - see the manuals and mailing list archives f= or=20 details. HTH --=20 Richard Huxton