qq_章鱼高_03773279
select sc.*, (
-- 子查询的意思是在score表中找出与当前记录cid相同,但score大于当前记录的score(sc.score)的数目+1。
-- 那样的话:如果是0, 则证明该条记录是表示的是该班的第一名,如果是1,在表示该班的第二名,以此类推。
select count(*) from Score as a where a.cid = sc.cid and a.score > sc.score
-- 所以后面加了个1
) +1 as px
from Score as sc order by sc.cid, px;做了个测试:SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for score
-- ----------------------------
DROP TABLE IF EXISTS `score`;
CREATE TABLE `score` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cid` int(11) DEFAULT NULL,
`score` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of score
-- ----------------------------
INSERT INTO `score` VALUES ('1', '1', '80');
INSERT INTO `score` VALUES ('2', '1', '70');
INSERT INTO `score` VALUES ('3', '1', '90');
INSERT INTO `score` VALUES ('4', '2', '80');
INSERT INTO `score` VALUES ('5', '3', '70');
INSERT INTO `score` VALUES ('6', '3', '60');
INSERT INTO `score` VALUES ('7', '2', '50');运行上面的sql查询,结果是:mysql> select sc.*, (
-> select count(*) from Score where cid = sc.cid and score > sc.score
-> ) + 1 as px
-> from Score as sc order by sc.cid, px;
+----+------+-------+------+
| id | cid | score | px |
+----+------+-------+------+
| 3 | 1 | 90 | 1 |
| 1 | 1 | 80 | 2 |
| 2 | 1 | 70 | 3 |
| 4 | 2 | 80 | 1 |
| 7 | 2 | 50 | 2 |
| 5 | 3 | 70 | 1 |
| 6 | 3 | 60 | 2 |
+----+------+-------+------+
7 rows in set (0.00 sec)