再求一SQL语句,谢谢!

dzmiao 2005-02-15 02:35:39
t1 -- 主题
id---cid---title
1-----1----城市广州XXX
2-----2----城市上海XXX
3-----3----情感亲情YYY
4-----4----情感爱情YYY
5-----5----食物面包KKK
6-----6----情感友情YYY
7-----5----食物面包KKK

tf -- 父类
fid---fname
1-----城市
2-----情感
3-----食物

tc -- 子类
cid---fid---cname
1-----1-----广州
2-----1-----上海
3-----2-----亲情
4-----2-----爱情
5-----3-----面包
6-----2-----友情


====现在需要返回各父类最新的N条记录,如最新2条:

id---cid---title
1-----1----城市广州XXX
2-----2----城市上海XXX (返回)
3-----3----情感亲情YYY
4-----4----情感爱情YYY (返回)
5-----5----食物面包KKK (返回)
6-----6----情感友情YYY (返回)
7-----5----食物面包KKK (返回)
8-----1----城市广州XXX (返回)

最终结果(id在各父类中倒序,fid按照升序或倒序都行,就是不能乱):

fid---id---cid---title
1-----8-----1----城市广州XXX
1-----2-----2----城市上海XXX
2-----6-----6----情感友情YYY
2-----4-----4----情感爱情YYY
3-----7-----5----食物面包KKK
3-----5-----5----食物面包KKK


请教各位,谢谢!
...全文
163 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
zjcxc 2005-02-15
  • 打赏
  • 举报
回复
t1表的数据多的话,建议用1楼的临时表
如果类别少,而t1表的数据多的话,建议用循环
数据少或追求一句完成任务,用我的方法
dzmiao 2005-02-15
  • 打赏
  • 举报
回复
select c.fid,a.* into #t from t1 a
join tc b on a.cid=b.cid
join tf c on b.fid=c.fid
select * from #t a
where id in (select top 2 id from #t where fid=a.fid order by id desc)
order by fid,id desc

select f.fid,a.id,c.cid,a.title
from t1 a,tf f,tc c
where f.fid=c.fid and c.cid=a.cid
and a.id in(
select top 2 aa.id
from t1 aa,tc cc
where aa.cid=cc.cid
and cc.fid=f.fid
order by aa.id desc)
order by f.fid,a.id desc,c.cid

=====都行,太强了

另外请问:在应用程序中需要显示如上数据,哪种方式效率较高?

通过一条SQL语句查询数据(即如上)

或者

先取得父类的fid,然后通过循环,一一检索所属各父类的主题

zjcxc 2005-02-15
  • 打赏
  • 举报
回复
select f.fid,a.id,c.cid,a.title
from t1 a,tf f,tc c
where f.fid=c.fid and c.cid=a.cid
and a.id in(
select top 2 aa.id
from t1 aa,tc cc
where aa.cid=cc.cid
and cc.fid=f.fid
order by aa.id desc)
order by f.fid,a.id desc,c.cid
zjcxc 2005-02-15
  • 打赏
  • 举报
回复
select a.id,c.cid,a.title
from t1 a,tf f,tc c
where f.fid=c.fid and c.cid=a.cid
and a.id in(
select top 2 aa.id
from t1 aa,tc cc
where aa.cid=cc.cid
and cc.fid=f.fid
order by aa.id desc)
zheninchangjiang 2005-02-15
  • 打赏
  • 举报
回复
偷懒的方法
select c.fid,a.* into #t from t1 a
join tc b on a.cid=b.cid
join tf c on b.fid=c.fid
select * from #t a
where id in (select top 2 id from #t where fid=a.fid order by id desc)
order by fid,id desc

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧