DELIMITER // DROPPROCEDUREIFEXISTS batchInsert; CREATEPROCEDURE batchInsert(n INT) BEGIN DECLARE i INT; SET i = 0; WHILE i < n DO INSERTINTO score(name, class, score) VALUES (substring(MD5(RAND()), 1, 10), CONCAT('G', ROUND(RAND() * 9)), ROUND(RAND() * 100)); SET i = i + 1; ENDWHILE; END // DELIMITER ; CALL batchInsert(50);
TOP N
HAVING子句中的< 3表示取前两条。
1 2 3 4 5
SELECT s1.class, s1.score FROM score s1 LEFTJOIN score s2 ON s1.class = s2.class AND s1.score <= s2.score GROUPBY s1.class, s1.score HAVINGCOUNT(1) < 3 ORDERBY s1.class, s1.score DESC;