pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Richard Huxton <dev@archonet.com>
To: Wei Weng <wweng@kencast.com>
To: pgsql-sql@postgresql.org
Subject: Re: How do you write this query?
Date: Thu, 31 Oct 2002 19:09:11 +0000
Message-ID: <200210311909.11341.dev@archonet.com> (raw)
In-Reply-To: <1036088486.13986.19.camel@Monet>
References: <1036088486.13986.19.camel@Monet>

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



view thread (4+ messages)  latest in thread

Message-ID: <200210311909.11341.dev@archonet.com>
Permalink:  ../200210311909.11341.dev@archonet.com/
Also on:    postgresql.org/message-id/200210311909.11341.dev@archonet.com

 · 

reply

Reply instructions:

You may reply publicly to this message via plain-text email
using any one of the following methods:

* Reply to all the recipients using the --to and --cc options:
  reply via email

  To: pgsql-sql@postgresql.org
  Cc: dev@archonet.com, wweng@kencast.com
  Subject: Re: How do you write this query?
  In-Reply-To: <200210311909.11341.dev@archonet.com>

* Save the following mbox file, import it into your mail client,
  and reply-to-all from there: mbox

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox