用一条sql查询出论坛每个版块下的最新6个帖子

论坛版块表:
图片描述

论坛帖子表:
图片描述

效果图:
图片描述

阅读 4k
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;

一条SQL语句做不到的,建议循环遍历所有版块,每个版块用 SELECT ... WHERE fid = ? ORDER BY dateline LIMIT 6 得到最新6条帖子,为提高效率,(fid, dateline)可以做成复合索引。

另外,用一条SQL语句查出每个版块最新的1条帖子,是能实现的,但不是件容易的事,试试看吧 :-)

用union,然后(fid, dateline)加上联合索引

非要一条语句的话 用 union

如果用的是MariaDB,已经可以支持window类的聚合函数,用法如下:

select *
from (
    select t1.*, ROW_NUMBER() OVER (PARTITION BY fid ORDER BY dateline desc) AS rn,
    from t1
) where rn <= 6
order by fid, dateline desc
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题