mysql中的GROUP BY max

时间:2013-03-15 23:50:21

标签: mysql

假设我有以下两个条目:

`id`     |    `timestamp`   |   `content`   |  `reference`
 1       |     2012-01-01   |    NEWER      |   1
 2       |     2013-01-01   |    NEWEST     |   1
 3       |     2011-01-01   |    OLD        |   2

我的查询需要以下结果:

`id`     |    `timestamp`   |   `content`   |  `reference`
 2       |     2013-01-01   |    NEWEST     |   1
 3       |     2011-01-01   |    OLD        |   2

这是我到目前为止所做的,但它是不正确的:

SELECT * FROM table GROUP BY reference

这里的正确查询是什么?

我希望获得每个引用ID的最新content段。在上面的示例中,有两个引用ID(1& 2),我想获取每个引用ID的最新条目。

3 个答案:

答案 0 :(得分:1)

SELECT * 
FROM (SELECT * FROM table ORDER BY timestamp desc) as sub
GROUP BY reference

如果您希望扩展查询,请将限制逻辑放入子查询中,以获得更好的性能:

SELECT * 
FROM (SELECT * 
      FROM table 
      WHERE 1=1 and 2=2
      ORDER BY timestamp desc
     ) as sub
GROUP BY reference

答案 1 :(得分:0)

我认为你想要每个参考的最新版本?像这样:

SELECT * FROM my_table
WHERE id IN (
  SELECT id FROM my_table ORDER BY timestamp DESC GROUP BY reference LIMIT 1
);

答案 2 :(得分:0)

select * from table where reference_id in 
    (select max(id) from table group by reference)