insert into B values(1,1,'a1'),(1,2,'a2'),(1,3,'a3'),(1,4,'a4');
insert into B values(2,1,'b1'),(2,2,'b2'),(2,3,'b3'),(2,4,'b4');
insert into B values(3,1,'c1'),(3,2,'c2'),(3,3,'c3'),(3,4,'c4');
+------+------+------+
| c1 | c2 | c3 |
+------+------+------+
| 1 | 1 | a1 |
| 1 | 2 | a2 |
| 1 | 3 | a3 |
| 1 | 4 | a4 |
| 2 | 1 | b1 |
| 2 | 2 | b2 |
| 2 | 3 | b3 |
| 2 | 4 | b4 |
| 3 | 1 | c1 |
| 3 | 2 | c2 |
| 3 | 3 | c3 |
| 3 | 4 | c4 |
+------+------+------+
12 rows in set (0.00 sec)
+------+------+------+------------------+
| c1 | c2 | c3 | rownum |
+------+------+------+------------------+
| 1 | 1 | a1 | 1 |
| 1 | 2 | a2 | 2 |
| 1 | 3 | a3 | 3 |
| 1 | 4 | a4 | 4 |
| 2 | 1 | b1 | 5 |
| 2 | 2 | b2 | 6 |
| 2 | 3 | b3 | 7 |
| 2 | 4 | b4 | 8 |
| 3 | 1 | c1 | 9 |
| 3 | 2 | c2 | 10 |
| 3 | 3 | c3 | 11 |
| 3 | 4 | c4 | 12 |
+------+------+------+------------------+
12 rows in set (0.00 sec)
CREATE TABLE `sam` (
`a` int(11) DEFAULT NULL,
`b` int(11) DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=utf8
2.插入模拟数据
INSERT INTO `sam` VALUES (1,10),(1,15),(1,20),(1,25),(2,20),(2,22),(2,33),(2,45);
+------+------+
| a | b |
+------+------+
| 1 | 10 |
| 1 | 15 |
| 1 | 20 |
| 1 | 25 |
| 2 | 20 |
| 2 | 22 |
| 2 | 33 |
| 2 | 45 |
+------+------+
3.SQL实现
(select ff.a,ff.b,@rownum:=@rownum+1 rownum,if(@pa=ff.a,@rank:=@rank+1,@rank:=1) as rank,@pa:=ff.a
FROM
(select a,b from sam group by a,b order by a asc,b desc) ff,(select @rank:=0,@rownum:=0,@pa=null) tt) result
having rank <=2;
4.结果:
+------+------+--------+------+
| a | b | rownum | rank |
+------+------+--------+------+
| 1 | 25 | 1 | 1 |
| 1 | 20 | 2 | 2 |
| 2 | 45 | 5 | 1 |
| 2 | 33 | 6 | 2 |
+------+------+--------+------+
4 rows in set (0.00 sec)