引出:信息表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
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
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