The answer to this question says a row with a max value on a column can be selected like so:
select yt.id, yt.rev, yt.contents
from YourTable yt
inner join(
select id, max(rev) rev
from YourTable
group by id
) ss on yt.id = ss.id and yt.rev = ss.rev
The answer to this question provides a similar solution:
SELECT tt.*
FROM topten tt
INNER JOIN
(SELECT home, MAX(datetime) AS MaxDateTime
FROM topten
GROUP BY home) groupedtt
ON tt.home = groupedtt.home
AND tt.datetime = groupedtt.MaxDateTime
The two solutions are essentially the same, just with different table and column names. They both return two columns in the INNER JOIN
, with one of them being the column MAX()
is being used on.
I know there are a bazillion greatest-n-per-group questions on here, but what I'm wondering is why only two columns can be returned when using MAX()
in an INNER JOIN
?
If all of the columns could be returned, then there wouldn't be a need for the INNER JOIN
(right?), so there must be a reason.
One last note: In the first query, the first column being returned appears to be a primary key. So my initial thought was maybe you can only return the primary key along with the column MAX()
is being used on. However, in the second query the first column being returned is home
and it isn't a primary key. So that blows my theory.