选择获取与MySQL组中的max对应的整个行 [英] Select get entire row corresponding to max in MySQL Group

查看:573
本文介绍了选择获取与MySQL组中的max对应的整个行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用GROUP BY后使用Max查找特定MySQL组中某个字段的最大值时,是否有可能获得包含最大值的整行?

When I use Max to find the maximum value of a field in a particular MySQL Group after using GROUP BY, is it possible to get the entire row which contains the maximum value?

推荐答案

在处理某些论坛代码时,我偶然发现了这个线程.我想获取每个线程的最新帖子,并将其显示在特定板的线程列表中.

I stumbled across this thread when working on some forum code. I wanted to get the latest post for each thread and display it in the list of threads for a particular board.

Quassnoi的上述回答对我非常有帮助,因此我能够进行调整.以下代码可以帮助其他人:

Quassnoi's answer above was very helpful to me and I was able to adapt it. Here is the code in case it helps anyone else:

SELECT p.id As post_id, p.post_number, p.topic_id
FROM forum_post p, (
    SELECT topic_id, MAX(post_number) As max_post_number
    FROM   forum_post d
    GROUP  BY topic_id) dd
WHERE p.id =
(
    SELECT id
    FROM   forum_post
    WHERE  topic_id = dd.topic_id
    AND    post_number = dd.max_post_number
    ORDER  BY topic_id DESC, post_number DESC, id DESC
    LIMIT  1
)

这篇关于选择获取与MySQL组中的max对应的整个行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆