0

我有以下 MySQL 查询:

Select match_static_id, comments as last_comment, max(timestamp)
from comments as c 
group by match_static_id;

我有对比赛的评论表,我想获得每场比赛的最新评论。所以我为此使用 max(timestamp) 和 group by (match_static_id) 但我的问题是我得到了按 match_static_id 分组的最大时间戳,但我得到了其他评论(不是最大时间戳的评论)我的查询是否以错误的方式排序?

4

2 回答 2

0

这将解决:

SELECT match_static_id, comments AS last_comment, login_time2
  FROM  comments c
WHERE timestamp=
    ( SELECT MAX(timestamp) AS login_time2
      FROM comments WHERE match_static_id=c.match_static_id)
 GROUP BY match_static_id;
于 2013-09-06T09:26:06.720 回答
0

我不是mysql专家,但我能感觉到这个问题。可能是因为注释不是 group by 的一部分,它会返回匹配 match_static_id 的所有行。我建议重写如下内容:

select match_static_id, (select Comment from comments c where c.timestamp =max(a.timestamp)) as last_comment, max(timestamp) from comments group by match_staic_id

或者

select c.match_static_id, c.comments as last_comment, c.timestamp from comments c inner join (Select max(timestamp) as ts from comments group by match_static_id) temp c.timestamp = temp.ts
于 2013-09-06T09:22:54.763 回答