简体   繁体   English

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

[英]Select get entire row corresponding to max in MySQL Group

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

我想知道这是否会奏效:

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

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's answer above was very helpful to me and I was able to adapt it. Quassnoi上面的答案对我很有帮助,我能够适应它。 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
)
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
        )

See this article for more explanations: 有关更多说明,请参阅此文章:

Look at the following query: 查看以下查询:

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

The idea is to sort table data by grouping field and sorted field and take the first row from each group 我们的想法是通过对字段和排序字段进行分组来对表数据进行排序,并从每个组中获取第一行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM