0

假设我有以下两个条目:

`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

这里正确的查询是什么?

我正在寻找content每个参考 id 的最新部分。在上面的示例中,有两个参考 ID(1 和 2),我想获取每个的最新条目。

4

3 回答 3

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
于 2013-03-15T23:57:14.620 回答
0

我认为您想要每个参考中的最新版本?像这样的东西:

SELECT * FROM my_table
WHERE id IN (
  SELECT id FROM my_table ORDER BY timestamp DESC GROUP BY reference LIMIT 1
);
于 2013-03-15T23:57:32.733 回答
0
select * from table where reference_id in 
    (select max(id) from table group by reference)
于 2013-03-15T23:57:50.150 回答