數據庫面試題:
其他關聯表這裏不一一寫出,僅寫出關鍵表(score)成績表
成績記錄id | scoreid |
---|---|
學生id | userid |
課程id | scoureid |
成績 | score |
現需要求出各科成績前三名的學生和成績,與相應的課程。
實現思路
用課程id自關聯一次成績表,如果相應課程成績高則排名越高。
SELECT * FROM `score` a WHERE
(SELECT COUNT(*) FROM `score` b WHERE a.`sourceid`= b.`sourceid` AND b.`score`>a.`score`)<3 -- 即成績前3
-- and (SELECT COUNT(*) FROM `score` b WHERE a.`sourceid`= b.`sourceid` AND b.`score`>a.`score`)>1-- 即成績爲第2名以後
ORDER BY sourceid,score DESC;
顯示結果:
又需要的可以嘗試一下,網上找了很多解決辦法,要麼使用高級函數,要麼邏輯很複雜,以下是建表語句
CREATE TABLE `score` (
`scoreid` int(11) NOT NULL AUTO_INCREMENT,
`sourceid` int(11) DEFAULT NULL,
`userid` int(11) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
PRIMARY KEY (`scoreid`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8;
相應數據SQL:
insert into `score`(`scoreid`,`sourceid`,`userid`,`score`) values (1,1,1,60),(2,2,1,80),(3,3,1,95),(4,1,2,75),(5,2,2,85),(6,3,2,90),(7,4,1,89),(8,4,2,88),(9,1,3,78),(10,2,3,87),(11,3,3,98),(12,4,3,76),(13,1,4,67),(14,2,4,76),(15,3,4,88),(16,4,4,77);