【问题标题】:Max function issue with the values from other columns来自其他列的值的最大函数问题
【发布时间】:2013-09-10 07:49:45
【问题描述】:

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

【问题讨论】:

  • 请提供一些输入输出模式。如果您可以在SQLFiddel.com提供演示,那将非常有帮助

标签: mysql groupwise-maximum


【解决方案1】:

我不是 mysql 方面的专家,但我能感觉到这个问题。可能是因为 cmets 不是 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

【讨论】:

    【解决方案2】:

    这样就解决了:

    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;
    

    【讨论】:

    • 这个查询给出了所有我只想获得具有最大时间戳的匹配项的评论
    • i want to have the latest comment of each match - 有EACH - naswer 中有简单的更新。
    • 好吧,我的朋友让我澄清一下,这是一个误会。我想要每个匹配的最后一条评论是正确的,但是在您的第一个查询中,我得到了所有匹配的所有 cmets,所有这些匹配的时间戳都相同(最大时间戳)。我只想要每场比赛的一条评论,即带有 max timestamp 的评论。我希望我现在清楚自己
    • 哦,我明白了。现在看。
    猜你喜欢
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 2015-01-12
    相关资源
    最近更新 更多