MySQL中没有Rank排名函数,当我们需要查询排名时,只能使用MySQL数据库中的基本查询语句来查询排名,下面有3种具体的实现。(ps:非特殊情况,实际开发尽量使用Redis的sortset去实现排行。)
接下来的排行实现都采用这个表的数据举例。(ps:建议直接跳过,只是方便测试而已。)
SET NAMES utf8mb4; SET FOREIGN_KEY_CHECKS = 0; DROP TABLE IF EXISTS `user`; CREATE TABLE `user` ( `id` int(0) NOT NULL AUTO_INCREMENT, `name` varchar(25) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci NULL DEFAULT NULL, `age` int(0) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_general_ci ROW_FORMAT = Dynamic; INSERT INTO `user` VALUES (1, 'a', 0); INSERT INTO `user` VALUES (2, 'b', 41); INSERT INTO `user` VALUES (3, 'c', 27); INSERT INTO `user` VALUES (4, 'd', 9); INSERT INTO `user` VALUES (5, 'e', 26); INSERT INTO `user` VALUES (6, 'f', 43); INSERT INTO `user` VALUES (7, 'g', 16); INSERT INTO `user` VALUES (8, 'h', 10); INSERT INTO `user` VALUES (9, 'i', 5); INSERT INTO `user` VALUES (10, 'j', 53); INSERT INTO `user` VALUES (11, 'k', 12); INSERT INTO `user` VALUES (12, 'l', 21); INSERT INTO `user` VALUES (13, 'm', 8); INSERT INTO `user` VALUES (14, 'n', 39); INSERT INTO `user` VALUES (15, 'o', 53); INSERT INTO `user` VALUES (16, 'p', 5); INSERT INTO `user` VALUES (17, 'q', 60); INSERT INTO `user` VALUES (18, 'r', 44); INSERT INTO `user` VALUES (19, 's', 41); INSERT INTO `user` VALUES (20, 't', 13); INSERT INTO `user` VALUES (21, 'u', 2); INSERT INTO `user` VALUES (22, 'v', 32); INSERT INTO `user` VALUES (23, 'w', 32); INSERT INTO `user` VALUES (24, 'x', 4); INSERT INTO `user` VALUES (25, 'y', 53); INSERT INTO `user` VALUES (26, 'z', 37); SET FOREIGN_KEY_CHECKS = 1;
SELECT id , name , age , @rank := @rank + 1 AS ageRank FROM user , ( SELECT @rank := 0 ) s ORDER BY age desc
SELECT id , name , age , CASE WHEN @ageValue = age THEN @rank WHEN @ageValue := age THEN @rank := @rank + 1 END AS ageRank FROM user , ( SELECT @rank := 0 , @ageValue := NULL ) s ORDER BY age desc
SELECT id , name , age , ageRank FROM ( SELECT id , name , age , @rank := IF( @ageValue = age ,@rank ,@realRank ) AS ageRank , @realRank := @realRank + 1 realRank, @ageValue := age ageValue FROM user , ( SELECT @rank := 0 , @ageValue := NULL , @realRank := 1) s ORDER BY age desc )t