mysql里面的
现在我要用SQL实现这样的一个功能:
表:article
字段:id,type,date...
type有1-10,10种类型
现在我要用SQL找出每种类型中时间最新的前N个数据组成集合我现在是这样写的
(select * from article where type=1 order by date limit 0,n) union(select
* from article where type=2 order by date limit 0,n)。。;大家教教我应该怎样写
group之后,把每组按date排序,再取每个group的前n个
现在我要用SQL实现这样的一个功能:
表:article
字段:id,type,date...
type有1-10,10种类型
现在我要用SQL找出每种类型中时间最新的前N个数据组成集合我现在是这样写的
(select * from article where type=1 order by date limit 0,n) union(select
* from article where type=2 order by date limit 0,n)。。;大家教教我应该怎样写
group之后,把每组按date排序,再取每个group的前n个
我现在也得到这样一个结果:
type=1 按时间字段date排序的前n条数据 和
type=2 按时间字段date排序的前n条数据 一直到 type=10
曾经想过做成多张表,但后来又觉得设计不合理 出了type意外所有的字段意义都相同 所以就放在了一张表中
SELECT * FROM article ORDER BY type, date limit 0,n;
select top N * from article order by type
select t, id, d from tb1 as a where a.d in (select d from tb1 as b where b.t=a.t order by d desc limit 2);
但是报错,因为limit不能用在子查询当中。
参见http://bbs.phpchina.com/thread-46680-1-1.html,讲了避免limit在子查询中报错的方法。自己试试吧,我是没辙了,看你人品,呵呵
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其中的2就是每组你上面说的n。