How to do that?
Former title of this question was "using rank (@Rank := @Rank + 1) in complex query with subqueries - will it work?" because I was looking for solution using ranks, but now I see that the solution posted by Bill is much much better.
Original question:
I'm trying to compose a query that would take last record from each group given some defined order:
SET @Rank=0;
select s.*
from (select GroupId, max(Rank) AS MaxRank
from (select GroupId, @Rank := @Rank + 1 AS Rank
from Table
order by OrderField
) as t
group by GroupId) as t
join (
select *, @Rank := @Rank + 1 AS Rank
from Table
order by OrderField
) as s
on t.GroupId = s.GroupId and t.MaxRank = s.Rank
order by OrderField
Expression @Rank := @Rank + 1
is normally used for rank, but for me it looks suspicious when used in 2 subqueries, but initialized only once. Will it work this way?
And second, will it work with one subquery that is evaluated multiple times? Like subquery in where (or having) clause (another way how to write the above):
SET @Rank=0;
select Table.*, @Rank := @Rank + 1 AS Rank
from Table
having Rank = (select max(Rank) AS MaxRank
from (select GroupId, @Rank := @Rank + 1 AS Rank
from Table as t0
order by OrderField
) as t
where t.GroupId = table.GroupId
)
order by OrderField
Thanks in advance!
So you want to get the row with the highest
OrderField
per group? I'd do it this way:(EDIT by Tomas: If there are more records with the same OrderField within the same group and you need exactly one of them, you may want to extend the condition:
end of edit.)
In other words, return the row
t1
for which no other rowt2
exists with the sameGroupId
and a greaterOrderField
. Whent2.*
is NULL, it means the left outer join found no such match, and thereforet1
has the greatest value ofOrderField
in the group.No ranks, no subqueries. This should run fast and optimize access to t2 with "Using index" if you have a compound index on
(GroupId, OrderField)
.Regarding performance, see my answer to Retrieving the last record in each group. I tried a subquery method and the join method using the Stack Overflow data dump. The difference is remarkable: the join method ran 278 times faster in my test.
It's important that you have the right index to get the best results!
Regarding your method using the @Rank variable, it won't work as you've written it, because the values of @Rank won't reset to zero after the query has processed the first table. I'll show you an example.
I inserted some dummy data, with an extra field that is null except on the row we know is the greatest per group:
We can show that the rank increases to three for the first group and six for the second group, and the inner query returns these correctly:
Now run the query with no join condition, to force a Cartesian product of all rows, and we also fetch all columns:
We can see from the above that the max rank per group is correct, but then the @Rank continues to increase as it processes the second derived table, to 7 and on higher. So the ranks from the second derived table will never overlap with the ranks from the first derived table at all.
You'd have to add another derived table to force @Rank to reset to zero in between processing the two tables (and hope the optimizer doesn't change the order in which it evaluates tables, or else use STRAIGHT_JOIN to prevent that):
But the optimization of this query is terrible. It can't use any indexes, it creates two temporary tables, sorts them the hard way, and even uses a join buffer because it can't use an index when joining temp tables either. This is example output from
EXPLAIN
:Whereas my solution using the left outer join optimizes much better. It uses no temp table and even reports
"Using index"
which means it can resolve the join using only the index, without touching the data.You'll probably read people making claims on their blogs that "joins make SQL slow," but that's nonsense. Poor optimization makes SQL slow.