mysql 排序學習---mysql
1、建表語句
CREATE TABLE `student` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(50) COLLATE utf8_bin NOT NULL COMMENT '姓名',
`score` int(11) NOT NULL COMMENT '成績,
`classid` int(11) NOT NULL COMMENT '班級',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=12 DEFAULT CHARSET=utf8 COLLATE=utf8_bin COMMENT='學生';
2、插入數據
insert into student(Name, Score, ClassId) values("lqh", 60, 1);
insert into student(Name, Score, ClassId) values("cs", 99, 1);
insert into student(Name, Score, ClassId) values("wzy", 62, 1);
insert into student(Name, Score, ClassId) values("zqc", 88, 2);
insert into student(Name, Score, ClassId) values("bll", 100, 2);
3、開始玩轉MySQL
查詢每個班級最大分數
select max(t.score) score,t.classid from student t group by t.classid
顯然這個在實際應用中不合場景,上面只能查出每個班級的最高分,但是是誰查不到
用下面這個語句,用分組的最高分、班級去原表中去匹配,命中出結果,就是相應的學生信息:
select s.* from student s join
(select max(t.score) score,t.classid from student t group by t.classid )r
on s.classid=r.classid and s.score=r.score
最高的第一名查出來了,但是比如我們要找前3名,前5名是誰,怎么搞?group by的max函數只能取最大值,前幾個怎么玩???
limit 3,limit 5,group 里面沒有這么玩的,limit只是對查出的結果做最外層的封裝
SELECT s1.* FROM student s1 WHERE ( SELECT count(DISTINCT(s2.score)) FROM student s2 WHERE s1.classid = s2.classid AND s2.score > s1.score ) < 2;
先給結果,但是這個我理解不了,為什么where條件為什么這樣寫?
select a.classid,a.`name`,a.score ,a.id ,b.id ,count(b.id)from student a left join student b on a.classid=b.classid and a.score<b.score GROUP BY a.classid,a.`name`,a.score having count(b.id)<2 order by a.classid,a.score
上面這個SQL就好理解多了
select a.classid,a.`name`,a.score ,a.id ,b.id ,count(b.id)from student a left join student b on a.classid=b.classid and a.score<b.score GROUP BY a.classid,a.`name`,a.score
先看這個,一下子就明白了,把a表中的每個成績都排個序,count(b.id)就是成績的排名,0就是第一,沒有比這個分數更高的,1就表示第二,只有一個比這個分數高的,依次類推
having count下 ,你要取前2名的話 having count就小於2,感覺這個好理解多了
https://blog.csdn.net/github_26672553/article/details/50800835