今天遇到一个问题,从产品数据库表中读出每个产品分类的最新的那一条产品的图片作为封皮,比如:产品中有分类 TypeA 、TypeB、TypeC,其中有很多的数据,如: id ? ? ? ?Type 1 ? ? ? ? ?TypeA 2 ? ? ? ? TypeA 3 ? ? ? ? TypeB 4 ? ? ? ? TypeA 5 ? ? ? ? TypeC 6 ? ? ? ??TypeC 也就是获得id分别为2、3、6的3条数据,于是乎出现了下面的**sql语句**

select ? id , Type from ?product a ?where ?( select ?count(1) ?from product b where a.Type = b.Type? and b.id >= a.id ) <=1

扩展一下,获得每个分类的最新的2条数据,那么sql语句该这样写:

select ? id , Type from ?product a ?where ?( select ?count(1) ?from product b where a.Type = b.Type? and b.id >= a.id ) <=2

继续扩展,获得每个分类的最旧的2条数据,那么sql语句该这样写:

select ? id , Type from ?product a ?where ?( select ?count(1) ?from product b where a.Type = b.Type? and b.id <= a.id ) <=2