From: Josh Berkus <josh@agliodbs.com>
To: Andrew Perrin <clists@perrin.socsci.unc.edu>
Cc: pgsql-sql@postgresql.org
Subject: Re: LIMIT within UNION?
Date: Thu, 12 Sep 2002 13:20:28 -0700
Message-ID: <200209121320.28318.josh@agliodbs.com> (raw)
In-Reply-To: <Pine.LNX.4.21.0209121540540.32000-100000@perrin.socsci.unc.edu>
References: <Pine.LNX.4.21.0209121540540.32000-100000@perrin.socsci.unc.edu>
Andrew,
Another approach, one that does not require you to know before constructing
the query how many eligible subjects there are, is not to use a union at all:
SELECT * FROM (
SELECT ... , zip
FROM participants
WHERE (typenr = 1 and <eligibility criteria)
OR (typenr = 2)
ORDER BY (typenr = 1 and <eligibility criteria>) DESC
LIMIT 200 ) p1
ORDER BY zip;
The inner query gives you all of the records that meet the eligibility
criteria, plus all of the records that have typenr = 2, in the order of
whether or not they meet the criteria (as a boolean value) and truncates it
at 200 records.
The outer query then re-sorts this result in zip order.
This seems, to me, much more flexible than using a UNION query.
--
-Josh Berkus
Aglio Database Solutions
San Francisco
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: josh@agliodbs.com, clists@perrin.socsci.unc.edu
Subject: Re: LIMIT within UNION?
In-Reply-To: <200209121320.28318.josh@agliodbs.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