select *
from t_tbl a
where
(select count(1)
from t_tbl b
where b.fid=a.fid and a.tid>b.tid)<6
order by fid,tid;
順序不一致就用下面的:
select aa.*
from
(select fid,tid,title,content,dateline,(@rownum:=@rownum+1) rn
from t_tbl,(select @rownum:=1) a
order by fid,dateline) aa
where
(select count(1)
from
(select fid,tid,title,content,dateline,(@rownum:=@rownum+1) rn
from t_tbl,(select @rownum:=1) a
order by fid,dateline) bb
where bb.fid=aa.fid and aa.rn>bb.rn)<6;
select
fid,title,content,dateline
from (
select
@gn:=case when @fid=fid then @gn+1 else 1 end gn,
@fid=fid fid,
title,
content,
dateline
from t_tbl,(select @gn:=1) a
order by fid,dateline) aa
where gn<7;
參考這個
一條SQL語句做不到的,建議循環遍歷所有版塊,每個版塊用
SELECT ... WHERE fid = ? ORDER BY dateline LIMIT 6
得到最新6條帖子,為提高效率,(fid, dateline)
可以做成複合索引。另外,用一條SQL語句查出每個版塊最新的1條帖子,是能實現的,但不是件容易的事,試試看吧 :-)
用union,然後(fid, dateline)加上聯合索引
非要一條語句的話 用
union
板塊很多的話union比較麻煩,下面一條sql可以得到結果
如果你的tid和dateline順序一致的話可以這麼寫:
順序不一致就用下面的:
··························分割線······················· ··············
補充一下,還可以引入組內行號,好像更簡單一些: