tags:

views:

110

answers:

3

My table looks something like:

ID | Type
01 | a
02 | c
03 | b
04 | a
05 | b
06 | a

I want to output the ID of the last added entries grouped by Type. ID is an auto-increment field so the last added entry is obviously the highest number.

SELECT * FROM `table` GROUP BY `Type` ORDER BY `ID` DESC, `Type` ASC

This groups the rows by Type then sorts by ID so I get IDs 1,2,3 whereas I want to sort first THEN group to get the result: 6,5,2

+1  A: 

If your MySQL version allows subselects (and 5.x does), this should work:

SELECT * 
    FROM (SELECT * FROM `table` ORDER BY `id` DESC) AS tmp 
    GROUP BY `type` 
    ORDER BY `type` ASC;
Christian Hang
A: 

Here's a classic way w/o subselects:

SELECT t1.* FROM table t1
LEFT JOIN table t2
  ON (t2.type = t1.type AND t2.id > t1.id)
WHERE t2.id IS NULL

read as "pick rows in the table such that no other row with the same type has a larger id".

Alex Martelli
+1  A: 

This might be what you're looking for ...

SELECT   MAX(`ID`), `Type`
FROM     `table`
GROUP BY `Type`
ORDER BY `Type` ASC

read as choose the maximum value of ID for each group of Type.

Convict
Works perfectly. Although the others are solutions, this is the simplest one I was after.
Peter
also noticed, you need to have MAX(`Type`) as well otherwise it doesn't pick the right one, especially if you have a few other columns
Peter