选择在MySQL Group中获取与max对应的整行

时间:2010-04-06 11:39:58

标签: mysql

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

4 个答案:

答案 0 :(得分:1)

我想知道这是否有效:

select * from table where id in (select distinct max(id) from table group by name)

答案 1 :(得分:1)

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

Quassnoi上面的答案对我很有帮助,我能够适应它。以下代码可以帮助其他人:

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
)

答案 2 :(得分:0)

SELECT  di.id, di.orderer, di.ghigh, di.glow
FROM    (
        SELECT  glow, MIN(orderer) AS orderer
        FROM    t_distinct d
        GROUP BY
                glow
        ) dd
JOIN    t_distinct di
ON      di.id =
        (
        SELECT  id
        FROM    t_distinct ds
        WHERE   ds.glow = dd.glow
                AND ds.orderer = dd.orderer
        ORDER BY
                glow DESC, orderer DESC, id DESC
        LIMIT 1
        )

有关更多说明,请参阅此文章:

答案 3 :(得分:0)

查看以下查询:

SELECT items.*
FROM items, (select @grouping_value:=null) as init
WHERE GREATEST(grouping_field=@grouping_value,
               IF(@grouping_value:=grouping_field,0,0))
ORDER BY grouping_field, sorted_field DESC

我们的想法是通过对字段和排序字段进行分组来对表数据进行排序,并从每个组中获取第一行