首页  >  文章  >  数据库  >  MySQL获取所有分类和每个分类的前N条记录

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

WBOY
WBOY原创
2016-06-07 17:53:071541浏览

本文章给大家介绍MySQL获取所有分类和每个分类的前N条记录,Article(Id,Category,InsertDate),现在要用SQL找出每种类型中时间最新的前N个数据组成的集合,一段不错的代码

 代码如下 复制代码
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                  GROUP BY A.Category,A.InsertDate
                 HAVING COUNT(B.InsertDate)     ) AS B1 
    ON A1.Category = B1.Category 
       AND A1.InsertDate = B1.InsertDate
ORDER BY A1.Category,A1.InsertDate DESC
声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn