MySQL获取所有分类和每个分类的前N条记录

2012/05/26 08:17
阅读数 5K

比如有文章表 Article(Id,Category,InsertDate),现在要用SQL找出每种类型中时间最新的前N个数据组成的集合,一段不错的代码,留存备用,转自(loveyuki.com),感谢。

SELECT A1.*  
FROM Article AS A1  
     INNER JOIN (SELECT A.Category,A.InsertDate 
                 FROM Article AS A  
                      LEFT JOIN Article AS B  
                        ON A.Category = B.Category  
                           AND A.InsertDate <= B.InsertDate  
                 GROUP BY A.Category,A.InsertDate 
                 HAVING COUNT(B.InsertDate) <= @N 
    ) AS B1  
    ON A1.Category = B1.Category  
       AND A1.InsertDate = B1.InsertDate 
ORDER BY A1.Category,A1.InsertDate DESC

@N 就是你要取多少条

展开阅读全文
打赏
1
4 收藏
分享
加载中
更多评论
打赏
0 评论
4 收藏
1
分享
返回顶部
顶部