本文章给大家介绍MySQL获取所有分类和每个分类的前N条记录,Article(Id,Category,InsertDate),现在要用SQL找出每种类型中时间最新的前N个数据组成的集合,一段不错的代码,代码如下:
- SELECTA1.*
- FROMArticleASA1
- INNERJOIN(SELECTA.Category,A.InsertDate
- FROMArticleASA
- LEFTJOINArticleASB
- ONA.Category=B.Category
- ANDA.InsertDate<=B.InsertDate
- GROUPBYA.Category,A.InsertDate
- HAVINGCOUNT(B.InsertDate)<=@N
- )ASB1--phpfensi.com
- ONA1.Category=B1.Category
- ANDA1.InsertDate=B1.InsertDate
- ORDERBYA1.Category,A1.InsertDateDESC