首先新建个表存积分最大值,方法是根据user_id分组汇总,sum出每组grade_num总和,然后排序选出最大的一个,所以表里只有一个数,把这部分放在子查询也可以。

然后连接user和grade_info两个表以取得所需字段,根据用户分组汇总并得到每组grade_num总和,然后限制grade_num总和等于之前得出的最大总和。

with get_max as
(select sum(grade_num) as max_grade from grade_info
group by user_id
order by max_grade desc limit 1)

select u.id, u.name, sum(grade_num) as grade_sum from
user as u, grade_info as g
where u.id = g.user_id
group by u.id
having sum(grade_num) = (select max_grade from get_max) 
order by u.id