我有以下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分组,但我得到其他评论(不是最大时间戳的评论) 我的查询是否以错误的方式排序?
答案 0 :(得分: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