gpt4 book ai didi

MySQL 详分割组

转载 作者:行者123 更新时间:2023-11-29 05:09:21 25 4
gpt4 key购买 nike

我有一张看起来像这样的 table ......

user_id, match_id, points_won
1 14 10
1 8 12
1 12 80
2 8 10
3 14 20
3 2 25

我想编写一个 MYSQL 脚本,它可以提取用户在单场比赛中赢得的最多分数,并在结果中包含 match_id - 换句话说......

user_id, match_id, max_points_won
1 12 80
2 8 10
3 2 25

当然,如果我不需要 match_id,我可以这样做......

select user_id, max(points_won)
from table
group by user_id

但是只要我将 match_id 添加到“select”和“group by”,我就会为每个匹配项添加一行,如果我只将 match_id 添加到“select”(而不是“group by”),那么它不会与 points_won 正确关联。

理想情况下,我也不想执行以下操作,因为它感觉不是特别安全(例如,如果用户在多场比赛中赢得了相同数量的积分)...

SELECT t.user_id, max(t.points_won) max_points_won
, (select t2.match_id
from table t2
where t2.user_id = t.user_id
and t2.points_won = max_points_won) as 'match_of_points_maximum'
FROM table t
GROUP BY t.user_id

这个问题有没有更优雅的选择?

最佳答案

这比在 MySQL 中需要的要难。一种方法有点 hack,但在大多数情况下都有效。这就是 group_concat()/substring_index() 技巧:

select user_id, max(points_won),
substring_index(group_concat(match_id order by points_won desc), ',', 1)
from table
group by user_id;

group_concat() 将所有 match_id 连接在一起,按点降序排列。 substring_index() 然后取第一个。

两个重要的警告:

  • 无论内部类型如何,结果表达式都是字符串类型。
  • group_concat() 使用内部缓冲区,其长度(默认情况下)为 1,024 个字符。此默认长度可以更改。

关于MySQL 详分割组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42175706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com