1. 程式人生 > >mysql分組排序

mysql分組排序

建表

create table tb_studscore_qlp(user_id varchar(10) charset utf8,type varchar(20)  charset utf8,score int);

insert into tb_studscore_qlp
select 'a' user_id,'語文' as type,95 as score 
union all
select 'a' user_id,'數學' as type,96 as score 
union all
select 'a' user_id,'英語' as type,86 as score 
union all
select 'a' user_id,'化學' as type,87 as score 
union all
select 'b' user_id,'語文' as type,85 as score 
union all
select 'b' user_id,'數學' as type,56 as score 
union all
select 'b' user_id,'英語' as type,75 as score 
union all
select 'b' user_id,'化學' as type,55 as score 
union all
select 'c' user_id,'數學' as type,68 as score 
union all
select 'c' user_id,'政治' as type,78 as score 
union all 
select 'c' user_id,'英語' as type,90 as score

查出每個使用者的分數最高的三門課程

1、關聯子查詢

select user_id, type, score 
from 
(select t1.*, (select count(*) from tb_studscore_qlp t2 where t2.user_id = t1.user_id and t2.score >= t1.score ) rn 
from tb_studscore_qlp t1 
order by user_id, rn ) t 
where rn <= 3;

結果如下:

a數學96
a語文95
a化學87
b語文85
b英語75
b數學56
c英語90
c政治78
c數學68

2、自連線

select
    t1.* from
    tb_studscore_qlp t1,
    tb_studscore_qlp t2
where
    t1.user_id = t2.user_id
and t2.score >= t1.score
group by
    t1.user_id,
    t1.type
having
    count(t2.score) <= 3
order by user_id,score desc

結果如下:

a數學96
a語文95
a化學87
b語文85
b英語75
b數學56
c英語90
c政治78

c數學68

3、子查詢

select * from tb_studscore_qlp a 
where exists 
(select count(1) from tb_studscore_qlp b where b.user_id = a.user_id and b.score > a.score having count(1) < 3 )
order by user_id,score desc

結果如下

a數學96
a語文95
a化學87
b語文85
b英語75
b數學56
c英語90
c政治78
c數學68