Let's say I need to find the oldest animal in each zoo. It's a typical maximum-of-a-group sort of query. Only here's a complication: the zebras and giraffes are stored in separate tables. To get a listing of all animals, be they giraffes or zebras, I can do this:
(SELECT id,zoo,age FROM zebras
UNION ALL
SELECT id,zoo,age FROM giraffes) t1
Then given t1
, I could build a typical maximum-of-a-group query:
SELECT t1.*
FROM t1
JOIN
(SELECT zoo,max(age) as max_age
FROM t1
GROUP BY zoo) t2
ON (t1.zoo = t2.zoo)
Clearly I could store t1
as a temporary table, but is there a way I could do this all within one query, and without having to repeat the definition of t1
? (Please let's not discuss modifications to the table design; I want to focus on the issue of working with the subquery result.)