MySQL获取所有分类的前N条记录
程序员文章站
2024-03-01 10:16:04
比如有文章表 article(id,category,insertdate),现在要用sql找出每种类型中时间最新的前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 <= 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 就是你要取多少条
下面是我用到了一个产品分类表中,superid是大分类,prcid是产品分类。能用sql完成的功能就要尽量用sql语句来完成,这既简洁又高效。
select a1.* from prckx as a1 inner join ( select a.superid, a.prcid from prckx as a left join prckx as b on a.superid = b.superid and a.prcid <= b.prcid group by a.superid, a.prcid having count(b.prcid) <= 7 ) as b1 on a1.superid = b1.superid and a1.prcid = b1.prcid order by superid, prcid
需求是这样的(csdn上的一个问题):mysql中有个表:article(字段:id,type,date),type有1-10,10种类型。现在要用sql找出每种类型中时间最新的前n个数据组成的集合。
这个问题应该有很多方法可以实现,下面就来说说在网上看到的一位高手的实现(用一条sql语句实现的,个人感觉非常好,所以拿来和大家分享):
select a1.* from article a1 inner join (select a.type,a.date from article a left join article b on a.type=b.type and a.date<=b.date group by a.type,a.date having count(b.date)<=2 )b1 on a1.type=b1.type and a1.date=b1.date order by a1.type,a1.date desc
注:上面sql语句中的2代表的就是前面提到的n。
以上所述就是本文的全部内容了,希望大家能够喜欢。