Home >Database >Mysql Tutorial >How to Efficiently Retrieve Records with the Highest or Lowest Values per Group in SQL?
Get Records with Highest/Smallest Values per Group
Problem:
Retrieve the records with the highest or smallest values for a given field within each group.
Former Proposed Solution:
Using ranks (@rank := @rank 1) in complex queries with subqueries.
Alternative Solution:
A more efficient approach is to utilize a left outer join without ranking variables:
SELECT t1.* FROM `Table` AS t1 LEFT OUTER JOIN `Table` AS t2 ON t1.GroupId = t2.GroupId AND t1.OrderField < t2.OrderField WHERE t2.GroupId IS NULL ORDER BY t1.OrderField;
This query achieves the desired result by leveraging an indexing strategy on (GroupId, OrderField) to optimize access to t2.
Optimization Considerations:
AND (t1.OrderField < t2.OrderField OR (t1.OrderField = t2.OrderField AND t1.Id < t2.Id))
Advantages of Left Outer Join Approach:
The above is the detailed content of How to Efficiently Retrieve Records with the Highest or Lowest Values per Group in SQL?. For more information, please follow other related articles on the PHP Chinese website!