Home >Database >Mysql Tutorial >How to Efficiently Find Max/Min Values per Group Using SQL Joins?
In this solution, we use a join operation to retrieve rows with the highest or lowest values for a specified column within each group, without resorting to ranking or subqueries.
To find the row with the highest OrderField value per group:
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;
In the event of multiple records sharing the same maximum OrderField value within a group, you may want to further refine the condition:
SELECT t1.* FROM `Table` AS t1 LEFT OUTER JOIN `Table` AS t2 ON t1.GroupId = t2.GroupId AND (t1.OrderField < t2.OrderField OR (t1.OrderField = t2.OrderField AND t1.Id < t2.Id)) WHERE t2.GroupId IS NULL
This approach ensures that the row with the greatest OrderField value is returned when there are ties within a group.
The above is the detailed content of How to Efficiently Find Max/Min Values per Group Using SQL Joins?. For more information, please follow other related articles on the PHP Chinese website!