MYSQL 如何查询分组排序后再对每组LIMIT n


遇到一个问题,有这样一个表:
mysql> desc recordMap;

   
  +-------------+---------------------+------+-----+---------+----------------
  
| Field | Type | Null | Key | Default | Extra
+-------------+---------------------+------+-----+---------+----------------
| id | int(11) unsigned | NO | PRI | NULL | auto_increment |
| mapId | int(10) unsigned | NO | | | |
| playTime | int(10) unsigned | NO | | |
| ...后面还有一些其他数据
+-------------+---------------------+------+-----+---------+----------------

mapId是地图Id,playTime是玩家玩这张地图用的时间,需求是查询对每一张地图,用时最少的N条记录。

我的方法(设N=2):

   
  SELECT id,mapId,playTime FROM recordMap a
  
WHERE 2 >
(
SELECT COUNT(1) FROM recordMap b
WHERE a.mapId=b.mapId AND a.playTime>b.playTime
)
ORDER BY mapId,playTime

这样做可以查出来,但是有个问题,如果表里面某个mapId的用时最短的记录>N条,会都查出来,如何限制只能查N条?
附:(有4个记录playTime都是最少的5,实际需求只想要2条)

   
  +----+-------+----------+
  
| id | mapId | playTime |
+----+-------+----------+
| 4 | 1000 | 5 |
| 5 | 1000 | 5 |
| 6 | 1000 | 5 |
| 7 | 1000 | 5 |
| 14 | 2000 | 15 |
| 12 | 2000 | 20 |
+----+-------+----------+

如果能简单说明一下原理最好,THX关注~

讨论 mysql

酒醉人自醉 12 years, 5 months ago

给你一个参考链接吧,实现起来挺复杂的,而且效率也不会很高,建议不要在mysql中实现
http://www.xaprb.com/blog/2006/12/07/how-to-select-the-firstleastmax-row-per-group-in-sql/

LITONG answered 12 years, 5 months ago

Your Answer