tags:

views:

102

answers:

3

When I use Max to find the maximum value of a field in a particular MySQL Group after using GROUP BY, is it possible to get the entire row which contains the maximum value?

+1  A: 

I wonder if this would work:

select * from table where id in (select distinct max(id) from table group by name)
Riho
You might get too many rows. Your statement returns all rows having an id which is the maximum of any group (not necessarily the group this row belongs to). Consider the following (id,name) pairs: (1,foo), (2,foo), (2,bar), (3,bar). You want to retrieve (2,foo) and (3,bar), but your query also returns (2,bar) since 2 is the max of the foo-group.
titanoboa
Added DISTINCT to select
Riho
A: 
SELECT  di.id, di.orderer, di.ghigh, di.glow
FROM    (
        SELECT  glow, MIN(orderer) AS orderer
        FROM    t_distinct d
        GROUP BY
                glow
        ) dd
JOIN    t_distinct di
ON      di.id =
        (
        SELECT  id
        FROM    t_distinct ds
        WHERE   ds.glow = dd.glow
                AND ds.orderer = dd.orderer
        ORDER BY
                glow DESC, orderer DESC, id DESC
        LIMIT 1
        )

See this article for more explanations:

Quassnoi
A: 

Look at the following query:

SELECT items.*
FROM items, (select @grouping_value:=null) as init
WHERE GREATEST(grouping_field=@grouping_value,
               IF(@grouping_value:=grouping_field,0,0))
ORDER BY grouping_field, sorted_field DESC

The idea is to sort table data by grouping field and sorted field and take the first row from each group

newtover