此分类搜索的存储过程如何写?
数据库中有两张表,分别为NewsClass、News这两张表的结构如下:
NewsClass:
ClassID
Class
News:
NewsID
ClassID
Title
通过ClassID使两张表产生关系,现在想实现这样的功能:从News表中查找出每个类别的前十条记录,用存储过程输出给程序使用。
问题点数:50、回复次数:2Top
1 楼didoleo(冷月无声)回复于 2005-01-24 12:53:39 得分 5
--测试数据,假设newsid不重复
create table NewsClass
(ClassID int,Class varchar(100))
insert into NewsClass
select 1,'opq' union all
select 2,'rst'
create table News
(NewsID int,ClassID int,Title varchar(100))
insert into News
select 1,1,'aaa' union all
select 2,1,'bbb' union all
select 3,1,'ccc' union all
select 4,1,'ddd' union all
select 5,1,'eee' union all
select 6,1,'fff' union all
select 7,1,'ggg' union all
select 8,1,'hhh' union all
select 9,1,'iii' union all
select 10,1,'jjj' union all
select 11,1,'kkk' union all
select 13,2,'aaaa' union all
select 14,2,'bbbb' union all
select 15,2,'cccc' union all
select 16,2,'dddd' union all
select 17,2,'eeee' union all
select 18,2,'ffff' union all
select 19,2,'gggg' union all
select 20,2,'hhhh' union all
select 21,2,'iiii' union all
select 22,2,'jjjj' union all
select 23,2,'kkkk'
select a.*,b.class from
(select * from news a where
(select count(1) from news where newsid<=a.newsid and classid=a.classid) between 1 and 10) a
left join newsclass b on a.classid=b.classid
order by a.classid,a.newsid
----------------------------------
1 1 aaa opq
2 1 bbb opq
3 1 ccc opq
4 1 ddd opq
5 1 eee opq
6 1 fff opq
7 1 ggg opq
8 1 hhh opq
9 1 iii opq
10 1 jjj opq
13 2 aaaa rst
14 2 bbbb rst
15 2 cccc rst
16 2 dddd rst
17 2 eeee rst
18 2 ffff rst
19 2 gggg rst
20 2 hhhh rst
21 2 iiii rst
22 2 jjjj rst
(所影响的行数为 20 行)Top
2 楼libin_ftsafe(子陌红尘:TS for Banking Card)回复于 2005-01-24 13:39:45 得分 45
select
a.*
from
News a
where
a.NewsID in(select
top 10 NewsID
from
News
where
ClassID=a.ClassID
order by
NewsID desc)Top




