简体   繁体   English

MySQL 按最大值选择 DISTINCT

[英]MySQL select DISTINCT by highest value

I have a table full of magazines, and need to extract the latest unique issue of each magazine.我有一桌子杂志,需要提取每本杂志的最新一期。

Ive tried我试过了

    SELECT DISTINCT
    magazine
        FROM
    product p
        INNER JOIN
    (SELECT 
        title, MAX(onSale) AS Latest
    FROM
        product
    GROUP BY magazine) groupedp

Which returns the distinct magazines , but not the rest of the data I require.它返回不同的杂志,但不返回我需要的其余数据。

UPDATE:更新:

schema模式

-id----onsale----magazine
  1    1/12/12   Fishing Mag
  2    1/11/12   Fishing Mag
  3    12/03/11  Pencil Sharpening Monthly
  4    1/02/10   Pencil Sharpening Monthly
  5    16/04/09  Homes in the Sky

So the result I would like returned would be:所以我想返回的结果是:

 -id----onsale----magazine
   1    1/12/12   Fishing Mag         
   3    12/03/11  Pencil Sharpening Monthly         
   5    16/04/09  Homes in the Sky
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 ;
SELECT id, MAX(onSale) as latest, magazine
FROM product
GROUP BY magazine
ORDER BY latest DESC

None of the given answers are correct, as they return an disassociated set of data that does not represent one exact row.给定的答案都不是正确的,因为它们返回一组不相关的数据,不代表一个确切的行。 The id may not be the id from the same row as the onsale value. id可能不是与onsale值来自同一行的id

The following will work:以下将起作用:

SELECT
    id, onsale, magazine
FROM (
    SELECT
       id, onsale, magazine
    FROM
        product
    ORDER BY
        onsale DESC) AS a
GROUP BY
    magazine

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 http://sqlfiddle.com/#!2/38e78/3

UPDATE: I've changed query a little, to return MAX(onsale)更新:我稍微改变了查询,返回 MAX(onsale)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM