pg.ddx.io  pgsql-sql@postgresql.org mailing list archive  
help / color / mirror / Atom feed
From: Tom Lane <tgl@sss.pgh.pa.us>
To: Thomas F. O'Connell <tfo@monsterlabs.com>
Cc: pgsql-sql@postgresql.org
Subject: Re: using top-level aggregate values in subqueries
Date: Mon, 23 Apr 2001 22:20:29 -0400
Message-ID: <25095.988078829@sss.pgh.pa.us> (raw)
In-Reply-To: <3AE4C818.5000804@monsterlabs.com>
References: <3AE4C818.5000804@monsterlabs.com>

"Thomas F. O'Connell" <tfo@monsterlabs.com> writes:
> select f.id
> from foo f, ola o
> where f.id = (
> 	select max( b.id )
> 	from bar b
> 	where b.bling = "i kiss you!"
> )
> and o.id != (
> 	select max( b.id )
> 	from bar b
> 	where b.bling = "i kiss you!"
> )

> is there some way to grab the value returned by the subquery in the 
> superquery and use the value instead of running the subquery twice?

In 7.1, perhaps something like this would do:

select f.id
from foo f, ola o,
	(select max( b.id ) as max
	 from bar b
	 where b.bling = "i kiss you!") ss
where f.id = ss.max
and o.id != ss.max

In prior versions you'd have to fake it by selecting the subquery
result into a temp table beforehand.

> i'm not looking for an optimized version of my example

While it's not a general solution, there's always transitivity:

select f.id
from foo f, ola o
where f.id = (
	select max( b.id )
	from bar b
	where b.bling = "i kiss you!"
)
and o.id != f.id

			regards, tom lane



view thread (3+ messages)  latest in thread

Message-ID: <25095.988078829@sss.pgh.pa.us>
Permalink:  ../25095.988078829@sss.pgh.pa.us/
Also on:    postgresql.org/message-id/25095.988078829@sss.pgh.pa.us

 · 

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 from your mail client; the link fills in
  the headers below: reply via email
  Some clients, webmail especially, drop In-Reply-To and References from
  a link, and the reply then starts a new thread: use the mbox below.

  To: pgsql-sql@postgresql.org
  Cc: tgl@sss.pgh.pa.us, tfo@monsterlabs.com
  Subject: Re: using top-level aggregate values in subqueries
  In-Reply-To: <25095.988078829@sss.pgh.pa.us>
  References: <3AE4C818.5000804@monsterlabs.com> <25095.988078829@sss.pgh.pa.us>

* 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