user表如下:
id | score | uid |
---|---|---|
1 | 100 | 1 |
2 | 100 | 1 |
3 | 90 | 1 |
4 | 80 | 2 |
5 | 90 | 2 |
6 | 70 | 2 |
7 | 80 | 3 |
8 | 60 | 3 |
sql查询如下:
方法1
select t.*
from user t //给表格重命名
where score = (select max(score) from user where uid = t.uid) group by t.uid;
方法2
select id,max(score),uid from user
GROUP BY uid
查询结果如下:
id | score | uid |
---|---|---|
1 | 100 | 1 |
5 | 90 | 2 |
7 | 80 | 3 |
若想要让所有最大值都显示,则使用如下方法:
select t.*
from user t
INNER JOIN (select MAX(score) as score ,uid from user GROUP BY uid) b
ON t.score=b.score and t.uid=b.uid
查询结果如下:
id | score | uid |
---|---|---|
1 | 100 | 1 |
2 | 100 | 1 |
5 | 90 | 2 |
7 | 80 | 3 |