Problem Statement
How can one efficiently retrieve the record with the highest or lowest value for a specific field within each group defined by another field?
Solution Using Left Outer Join
To retrieve the record with the highest value for the OrderField field within each GroupId, use the following query:
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;
Benefits of Join Approach
Alternatives
If the data is small or the specific implementation of the database engine you are using is poorly optimized for joins, you may consider alternatives such as:
Inefficiency of Method Using @Rank Variable
The method you described using the @Rank variable, as originally written, will not work correctly because the @Rank variable does not reset to zero after processing the first table. To fix this, you would need to add another derived table to reset @Rank to zero before processing the second table. However, this approach is still inefficient compared to the join approach.
The above is the detailed content of How Can I Efficiently Retrieve the Highest or Lowest Record per Group in a Database?. For more information, please follow other related articles on the PHP Chinese website!