Using an Exclusive Join to get the Last Item of a Group Print

  • 6

How to select a list of the highest or lowest items using a joined column.  In the following example, the item column represents your shared pointer and the value column represents your comparison value.  The value column could be any SQL datatype that supports a comparison operator.

Example Table

id | item | value
1  | 5    |  1
2  | 5    |  2
3  | 5    |  8
4  | 6    |  5
5  | 6    |  8

Query to select the Lowest Value

SELECT t1.*
FROM `table` AS `t1`
LEFT JOIN `table` AS `t2` ON `t1`.`id` = `t2`.`id` AND `t1`.`value` > `t2`.`value`
WHERE `t2`.`id` IS NULL

Query Result

id | item | value
3  | 5    |  8
5  | 6    |  8

Query to select the Highest Value (Change the Operator)

SELECT t1.*
FROM `table` AS `t1`
LEFT JOIN `table` AS `t2` ON `t1`.`id` = `t2`.`id` AND `t1`.`value` < `t2`.`value`
WHERE `t2`.`id` IS NULL

Query Result

id | item | value
3  | 5    |  8
5  | 6    |  8

Source: http://forums.mysql.com/read.php?20,111452

Was this answer helpful?

« Back