Given a table structure with name and rank columns, with the possibility of there being duplicates for name, how can I get the rows unique by name, with maximum rank?
For example, assuming the following data:
+-------+-------+
| name | rank |
+-------+-------+
| a | 1 |
| a | 2 |
| b | 10 |
| b | 20 |
| c | 100 |
| c | 200 |
+-------+-------+
The query should return:
+-------+-------+
| a | 2 |
| b | 20 |
| c | 200 |
+-------+-------+
I have the following solution that is extremely slow, which I suspect is O(N^2).
SELECT name,
rank
FROM books temp1
WHERE rank = (SELECT max(rank)
FROM book temp2
WHERE temp1.name = temp2.name)
Can it be improved? Is there an altogether better way to do this?
I’m using MySQL, and this will eventually have to be translated to JPA, so if there’s a JPA/Hibernate idiom for this that would also be very appreciated.
1 Answer