引出:信息表NEWS[nid,ntitle,cid,cdate......]

栏目表COLUMN[cid,cname....]

新闻表里CID有与栏目表的外键约束 ,现在要想查询10篇最新文章,按信息添加顺序,每个栏目一篇,即按时间排序、按栏目排序,每个栏目一篇!

 

开始想用连接、游标来实现,太麻烦,先提供一下思路,希望对有同样需要的朋友有帮助:

 

连接查询最新唯一记录的方法select top 100 b.nid,b.cid from Column a left join News b
连接查询最新唯一记录的方法
on a.cid=b.cid 
连接查询最新唯一记录的方法
and not exists(select 1 from News where cid=b.cid and nid>b.nid )
连接查询最新唯一记录的方法
order by b.cdate desc


测试:

 

连接查询最新唯一记录的方法declare @t1 table(cid varchar(10),cname varchar(10))
连接查询最新唯一记录的方法
insert @t1 select 'A01'  ,  'tom'
连接查询最新唯一记录的方法
insert @t1 select 'A02'  ,  'mary'
连接查询最新唯一记录的方法
insert @t1 select 'A03'  ,  'gary'
连接查询最新唯一记录的方法
连接查询最新唯一记录的方法
declare @t2 table(classid varchar(10),empid varchar(10),cname varchar(10))
连接查询最新唯一记录的方法
insert @t2 select 'C01'   ,    'A01'  ,  'english'
连接查询最新唯一记录的方法
insert @t2 select 'C02'   ,    'A01'  ,  'math'
连接查询最新唯一记录的方法
insert @t2 select 'C03'   ,    'A02'  ,  'physics'
连接查询最新唯一记录的方法
连接查询最新唯一记录的方法
select 连接查询最新唯一记录的方法a.empid,b1.classid,a.name,b1.cname
连接查询最新唯一记录的方法
from @t1 a
连接查询最新唯一记录的方法
left join @t2 b1连接查询最新唯一记录的方法
连接查询最新唯一记录的方法
on a.empid=b1.empid and not exists (select 1 from @t2 where empid=b1.empid and classid<b1.classid)
连接查询最新唯一记录的方法
连接查询最新唯一记录的方法
--结果
连接查询最新唯一记录的方法

连接查询最新唯一记录的方法 empid      classid    name       cname     
连接查询最新唯一记录的方法
---------- ---------- ---------- ---------- 
连接查询最新唯一记录的方法
连接查询最新唯一记录的方法A01        C01        tom        english
连接查询最新唯一记录的方法连接查询最新唯一记录的方法A02        C03        mary       physics
连接查询最新唯一记录的方法连接查询最新唯一记录的方法A03        
NULL       gary       NULL

 

相关文章:

  • 2021-07-12
  • 2022-12-23
  • 2021-11-23
  • 2022-02-25
  • 2021-11-25
  • 2021-06-13
  • 2021-12-07
  • 2022-02-09
猜你喜欢
  • 2022-12-23
  • 2021-11-17
  • 2022-12-23
  • 2021-10-30
  • 2021-11-07
  • 2022-01-20
相关资源
相似解决方案