【问题标题】:MySQL query problem on group by and max关于 group by 和 max 的 MySQL 查询问题
【发布时间】:2010-06-14 08:07:55
【问题描述】:

我的表结构是 (id,cluster,qid,priority)。我试图弄清楚如何显示每个集群的最大优先级值。假设集群 1 的优先级为 100、102、105。我想显示包含 105 的记录。请帮忙。

【问题讨论】:

  • 请张贴你已经拥有的东西

标签: mysql group-by max aggregate-functions


【解决方案1】:

这里有一篇文章解释了如何为每个组选择具有最大值的行。

http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

【讨论】:

    【解决方案2】:
    select cluster, MAX(priority) from structure group by cluster;
    

    要查找所有列,请尝试

    select *  from structure
    where priority = (
                    select MAX(priority) from structure as s 
                    where s.cluster = structure.cluster
                  );
    

    【讨论】:

    • 不,这行不通。它不会为集群返回具有最大优先级的记录。只显示最大值。
    【解决方案3】:

    您可以使用内部连接过滤掉行,例如:

    select  s.*
    from    structure s
    join    (
            select  cluster, MAX(priority) maxprio
            from    structure 
            group by 
                    cluster
            ) filter
    on      s.cluster = filter.cluster
            and s.priority = filter.maxprio
    

    如果它们都具有该集群的最大优先级,这将返回多行。

    【讨论】:

    • 这行得通!感谢您的即时帮助。与逻辑 xaprb.com/blog/2006/12/07/… 相比,这似乎有点慢。如果您愿意,请尝试检查一下。
    猜你喜欢
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-16
    • 2022-01-04
    • 1970-01-01
    • 1970-01-01
    • 2019-02-11
    相关资源
    最近更新 更多