MySQL MAX query help

Discussion in 'MySQL' started by dpak, May 1, 2006.

  1. #1
    Does anyone know how to do a mysql query to select the row in a table with the maximum value? So for instance, I have a table with

    Name - Value - Data
    Joe - 1 - SomeData1
    Joe - 2 - SomeData2
    Bob - 1 - SomeData1
    Bob - 2 - SomeData2
    Steve - 1 - SomeData1
    Steve - 3 - SomeData3

    I want to select so the results are:

    Name - Value - Data
    Joe - 2 - SomeData2
    Bob - 2 - SomeData2
    Steve - 3 - SomeData3

    I could just use a GROUP BY and the MAX function, except that the data field is not the same for all rows.

    Thanks in advance for your help!
     
    dpak, May 1, 2006 IP
  2. Slapyo

    Slapyo Well-Known Member

    Messages:
    266
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    108
    #2
    not sure if this would work but worth a shot.
    select name, max(value), data from table group by name, data
    Code (markup):
     
    Slapyo, May 2, 2006 IP
  3. Owen

    Owen Peon

    Messages:
    10
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Close, but not quite:
    
    select name,value, data from table group by name having max(value)
    
    Code (markup):
    Hope this helps.
    Owen
     
    Owen, May 2, 2006 IP
    exam likes this.
  4. Edmunds

    Edmunds Peon

    Messages:
    136
    Likes Received:
    5
    Best Answers:
    0
    Trophy Points:
    0
    #4
    I don't think that will work at all. In fact, it just doesn't on my MySQL installation. What you'd have to do is select the max value, and then query for that row again.

    What I'm saying is correct. See how MySQL.com does it: http://dev.mysql.com/doc/refman/4.1/en/example-maximum-row.html
     
    Edmunds, May 5, 2006 IP
  5. Owen

    Owen Peon

    Messages:
    10
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    0
    #5
    Oops. Right you are... I forgot about that MySQL limitation. You could do an order by desc to get the desired results in one query. Take a look at the comments from that MySQL page for an example.

    Owen
     
    Owen, May 6, 2006 IP