Grouping by Column with Dependence on another Column

mysql, php, sql

Solution

Try this one, the idea behind the subquery is that it gets the latest `ID` for each `Name` using `MAX` (aggregate function). Then join it against the table itself on the two columns of the subquery.

SELECT  a.*
FROM    tableName a
        INNER JOIN 
        (
            SELECT name, MAX(ID) maxID
            FROM tableName
            GROUP BY name
        ) b ON a.Name = b.Name AND
                a.ID = b.MaxID

- SQLFiddle Demo

Problem

Here is a simplified look at the problem I am trying to cleanly solve via a MySQL query. This is not the actual table I am dealing with. If I have the following table: ``` Name Buyer ID John Fred 4 John Smith 3 Fred Sally 2 John Kelly 1 ``` I would like a query to return the following: ``` Name Buyer ID John Fred 4 Fred Sally 2 ``` Such that we group by 'name' and show the latest row / buyer / ID. I tried to implement this by performing a nested select statement, wherein I first performed "ORDER BY ID DESC" then, on the outermost SELECT, "GROUP BY NAME". And, while this is a roundabout way of solving the problem, it seemed that, by virtue of the ordering, the correct selection would be returned to me. Unfortunately, "GROUP BY" does not 'guarantee' that the 'Buyer' column will contain the expected entry. Any helpful suggests for implementing this as a query? At the moment, I have a highly-inefficient PHP 'version' of the query running on a large table dump - definitely not the best choice.

Original source

Related problems