MySQL以最高值选择DISTINCT

时间:2012-07-11 13:48:44

标签: mysql

我有一张满是杂志的桌子,需要提取每本杂志的最新独特刊物。

我试过

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

返回不同的杂志,但不返回我需要的其他数据。

更新:

模式

-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

所以我想要的结果是:

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

5 个答案:

答案 0 :(得分:8)

SELECT id, MAX(onSale) as latest, magazine
FROM product
GROUP BY magazine
ORDER BY latest DESC

答案 1 :(得分:6)

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 ;

答案 2 :(得分:2)

这看起来像你需要的:

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

请查看:

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

<强>更新 我稍微改了一下查询,返回MAX(onsale)

答案 3 :(得分:1)

给出的答案中没有一个是正确的,因为它们返回的一组分离的数据不代表一个确切的列。 id可能不是与id值同一行的onsale

以下将起作用:

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

答案 4 :(得分:-1)

您需要将“其余数据”放在第一个选择中:

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