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 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)