php - 用一条sql查询出论坛每个版块下的最新6个帖子
本文介绍了php - 用一条sql查询出论坛每个版块下的最新6个帖子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
论坛版块表:
论坛帖子表:
效果图:
解决方案
板块很多的话union比较麻烦,下面一条sql可以得到结果
如果你的tid和dateline顺序一致的话可以这么写:
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;
这篇关于php - 用一条sql查询出论坛每个版块下的最新6个帖子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文