duanhui5344 2014-10-21 09:32
浏览 103
已采纳

MySQL GROUP BY不连贯

I'm having an issue with a query, and more specifically the GROUP BY function.

The query works perfectly and returns the right results in the right order, but when I try to group by user ID, it messes up everything.

SELECT u.ID, GREATEST( IF(c.climb_length >= 1, r.cotation_1, 0)
, IF(c.climb_length >= 2, r.cotation_2, 0)
, IF(c.climb_length >= 3, r.cotation_3, 0)
, IF(c.climb_length >= 4, r.cotation_4, 0)
, IF(c.climb_length >= 5, r.cotation_5, 0)
, IF(c.climb_length >= 6, r.cotation_6, 0)
, IF(c.climb_length >= 7, r.cotation_7, 0)
, IF(c.climb_length >= 8, r.cotation_8, 0)
, IF(c.climb_length >= 9, r.cotation_9, 0)
, IF(c.climb_length >= 10, r.cotation_10, 0)
) AS vmax
FROM users u
INNER JOIN climbs c
ON c.user_id = u.ID
INNER JOIN routes r
ON c.route_id = r.ID
GROUP BY vmax, u.ID
ORDER BY vmax DESC

This returns something like that, which is close to what I want, except for the duplicate u.IDs (usernames displayed for readability):

The problem is, I only want the highest vmax per u.ID - each u.ID appearing only once. So if I do the same request but with only GROUP BY u.ID, I get this, which makes no sense:

Here, the vmax values are wrong, hence the order is wrong. I don't even understand where those values come from: the vmax value for each u.ID does not even match the last inserted vmax of each user as calculated by the query (I can show that if I add c.ID in the SELECT part), nor the first one. They do belong to each user, but they are all over the place chronologically.

I have tried many things, researched and read a lot (for example this link seemed promising), but it doesn't make much sense to me that this last bit above does not work. Does anyone see where I messed up?

Thanks!

  • 写回答

1条回答 默认 最新

  • dongqi8863 2014-10-21 09:42
    关注

    Use aggregate function MAX and group by u.ID only:

    SELECT u.ID, MAX(GREATEST( IF(c.climb_length >= 1, r.cotation_1, 0)
    , IF(c.climb_length >= 2, r.cotation_2, 0)
    , IF(c.climb_length >= 3, r.cotation_3, 0)
    , IF(c.climb_length >= 4, r.cotation_4, 0)
    , IF(c.climb_length >= 5, r.cotation_5, 0)
    , IF(c.climb_length >= 6, r.cotation_6, 0)
    , IF(c.climb_length >= 7, r.cotation_7, 0)
    , IF(c.climb_length >= 8, r.cotation_8, 0)
    , IF(c.climb_length >= 9, r.cotation_9, 0)
    , IF(c.climb_length >= 10, r.cotation_10, 0)
    )) AS vmax
    FROM users u
    INNER JOIN climbs c
    ON c.user_id = u.ID
    INNER JOIN routes r
    ON c.route_id = r.ID
    GROUP BY u.ID
    ORDER BY vmax DESC
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢
  • ¥15 不小心不正规的开发公司导致不给我们y码,
  • ¥15 我的代码无法在vc++中运行呀,错误很多
  • ¥50 求一个win系统下运行的可自动抓取arm64架构deb安装包和其依赖包的软件。
  • ¥60 fail to initialize keyboard hotkeys through kernel.0000000000
  • ¥30 ppOCRLabel导出识别结果失败
  • ¥15 Centos7 / PETGEM
  • ¥15 csmar数据进行spss描述性统计分析
  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了