Re: How do you write this query?

From: Jean-Luc Lachance <jllachan(at)nsd(dot)ca>
To: Richard Huxton <dev(at)archonet(dot)com>
Cc: Wei Weng <wweng(at)kencast(dot)com>, pgsql-sql(at)postgresql(dot)org
Subject: Re: How do you write this query?
Date: 2002-10-31 20:38:20
Message-ID: 3DC194BC.966E95CD@nsd.ca
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-sql

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

In response to

Browse pgsql-sql by date

  From Date Subject
Next Message Achilleus Mantzios 2002-11-01 07:51:04 Re: How do you write this query?
Previous Message Richard Huxton 2002-10-31 19:09:11 Re: How do you write this query?