MySQL select DISTINCT by highest value

后端 未结 5 565
刺人心
刺人心 2021-01-05 06:52

I have a table full of magazines, and need to extract the latest unique issue of each magazine.

Ive tried

    SELECT DISTINCT
    magazine
        F         


        
相关标签:
5条回答
  • 2021-01-05 07:04
    SELECT id, MAX(onSale) as latest, magazine
    FROM product
    GROUP BY magazine
    ORDER BY latest DESC
    
    0 讨论(0)
  • 2021-01-05 07:15

    None of the given answers are correct, as they return an disassociated set of data that does not represent one exact column. The id may not be the id from the same row as the onsale value.

    The following will work:

    SELECT
        id, onsale, magazine
    FROM (
        SELECT
           id, onsale, magazine
        FROM
            product
        ORDER BY
            onsale DESC) AS a
    GROUP BY
        magazine
    
    0 讨论(0)
  • 2021-01-05 07:19

    You need to put the 'rest of data' in the first select:

    SELECT DISTINCT magazine, "rest of data"
    FROM product p 
    INNER JOIN 
    ( SELECT title, MAX(onSale) AS Latest 
    FROM product 
    GROUP BY magazine ) groupedp
    
    0 讨论(0)
  • 2021-01-05 07:22
    SELECT 
        p.*
    FROM
            product p
        INNER JOIN
            ( SELECT 
                  magazine, MAX(onSale) AS latest
              FROM
                  product
              GROUP BY 
                  magazine
            ) AS groupedp
          ON  groupedp.magazine = p.magazine
          AND groupedp.latest = p.onSale ;
    
    0 讨论(0)
  • 2021-01-05 07:26

    This looks like what you need:

    SELECT id, MAX(onsale) AS onsale, magazine FROM magazines GROUP BY magazine ORDER BY onsale DESC;
    

    Check it out at:

    http://sqlfiddle.com/#!2/38e78/3

    UPDATE: I've changed query a little, to return MAX(onsale)

    0 讨论(0)
提交回复
热议问题