tags:

views:

147

answers:

2

Say for instance I have a table which has names of people and their ages. I want a generic query in MySQL which will pull out the n oldest people.

I could use something like this:

SELECT * FROM people ORDER BY age DESC LIMIT 1;

Say Frank and Emily are both 99 years old. The limit 1 will only return one of their names. In psuedo-sql I would want the query to look like this:

SELECT * FROM people WHERE MAX(age);

I know you can also do this with a subquery, but there must be an easier, more generic way of achieving this?

+2  A: 

Nope, subquery is it. For example, everyone with the top 3 ages:

SELECT * FROM people WHERE age IN (SELECT DISTINCT age FROM people ORDER BY age DESC LIMIT 3)

or just the top age:

SELECT * FROM people WHERE age = (SELECT MAX(age) FROM people)
cletus
Cletus, why would you use a LIMIT in the subquery rather than the MAX aggregate? And if you're doing a limit 1, why the DISTINCT?
tpdi
You're quite right. Corrected.
cletus
Coolio. Bah, the subquery seems a little awkward.
Chris Lloyd
+1  A: 

I know you can also do this with a subquery, but there must be an easier, more generic way of achieving this?

Not in ANSI SQL.

SELECT * FROM people WHERE age = 
  (select MAX(age) from people);
tpdi
I disagree: this is ANSI/ISO SQL without a subquery: SELECT P1.ID, P2.Age FROM people AS P1 INNER JOIN people AS P2 ON P1.ID = P2.ID GROUP BY P1.ID, P2.AgeHAVING P1.Age = MAX(P2age);
onedaywhen
Oops, ignore comment (I can't delete it).
onedaywhen