Home  >  Article  >  Database  >  MySQL 获取所有归类和每个分类的前几条记录

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

WBOY
WBOYOriginal
2016-06-07 16:23:301339browse

MySQL 获取所有分类和每个分类的前几条记录 比如有文章表 Article(Id,Category,InsertDate) 现在要用SQL找出每种类型中时间最新的前N个数据组成的集合 SELECT A1.*FROM Article AS A1INNER JOIN (SELECT A.Category,A.InsertDateFROM Article AS ALEFT JOIN A

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

比如有文章表 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 <= 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

?

ps: ?@N 就是要取多少条

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn