mysql實現topN top1


  有時會碰到一些需求,查詢分組后的最大值,最小值所在的整行記錄或者分組后的top n行的記錄,像在hive中是有窗口函數的,可以通過它們來實現,但是MySQL沒有這些函數,可通過下面的方法來實現

1、准備

create table `test1` (
  `id` int(11) not null auto_increment,
  `name` varchar(20) default null,
  `course` varchar(20) default null,
  `score` int(11) default null,
  primary key (`id`)
) engine=innodb auto_increment=10 default charset=utf8


insert into test1(name,course,score)
values 
('張三','語文',80),
('李四','語文',90),
('王五','語文',93),
('張三','數學',77),
('李四','數學',68),
('王五','數學',99),
('張三','英語',90),
('李四','英語',50),
('王五','英語',89);

2、TOP 1

  需求:查詢每門課程分數最高的學生以及成績

  實現方法:可以通過自連接、子查詢來實現,如下

  a、自連接實現

select a.name,a.course,a.score 
from test1 a  join (select course,max(score) score from test1 group by course) b  
on a.course=b.course and a.score=b.score;

  執行效果如下

        

  b、子查詢實現

select name,course,score 
from test1 a  
where score=(select max(score) from test1 where a.course=test1.course);

  執行效果如下

        

  也可以用下面這個子查詢實現

select name,course,score 
from test1 a 
where not exists(select 1 from test1 where a.course=test1.course and a.score < test1.score);

  執行效果如下

      

 

3、TOP N

  需求:查詢每門課程前兩名的學生以及成績

  實現方式:使用union all、自身左連接、子查詢、用戶變量等方式實現

  a、使用union all實現

(select name,course,score from test1 where course='語文' order by score desc limit 2)
union all
(select name,course,score from test1 where course='數學' order by score desc limit 2)
union all
(select name,course,score from test1 where course='英語' order by score desc limit 2);

  執行效果如下

        

  b、使用自身左連接

select a.name,a.course,a.score 
from test1 a left join test1 b on a.course=b.course and a.score<b.score
group by a.name,a.course,a.score
having count(b.id)<2
order by a.course,a.score desc;

  執行效果如下

        

  c、使用子查詢

select *
from test1 a
where 2>(select count(*) from test1 where course=a.course and score>a.score)
order by a.course,a.score desc;

  執行效果如下

        

  d、使用用戶變量

set @num := 0, @course := '';

select name, course, score
from (
select name, course, score,
@num := if(@course = course, @num + 1, 1) as row_number,
@course := course as dummy
from test1
order by course, score desc
) as x where x.row_number <= 2;

  執行效果如下

 

 

如果,您認為閱讀這篇博客讓您有些收獲,不妨點擊一下右下角的【推薦】。
如果,您希望更容易地發現我的新博客,不妨點擊一下左下角的【關注我】。
如果,您對我的博客所講述的內容有興趣,請繼續關注我的后續博客,我是【劉超★ljc】。

本文版權歸作者,禁止轉載,否則保留追究法律責任的權利。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM