I have a single table that looks like this:
Table: id, name
A name can show up many times. I’m trying to figure out an optimal query that will return for each name, its highest ID.
input data:
1, "a"
2, "a"
3, "b"
4, "a"
5", "b"
output:
4, "a"
5, "b"
I know of a way to do this using a subquery in the FROM portion of the query. I’m hoping I can somehow do faster.
I currently do:
SELECT table.*
FROM table, (SELECT MAX(id) maxid FROM table GROUP BY name) maxids
WHERE table.id = maxids.maxid
I am curious to see if there are faster ways!
Why use the self-join, this should work just fine:
See SQL Fiddle with Demo
Now if you have more columns, that you want to include in your final result then you can use the following:
Or even:
See SQL Fiddle with Demo of both