日期:2014-05-18  浏览次数:20395 次

送分100!!!! 简单SQL问题!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
我有一个存储新闻分类的表(mulu)字段如下:
mulu_id   (int)   分类表里用的唯一ID,自动生成
mulu_fid   (int)   父ID,0表示根目录
mulu_name   (varchar(255))   分类名称

还有一个存储新闻内容的表(news)主要字段如下:
news_id   (int)   新闻表里唯一ID,自动生成
mulu_id   (int)   对应mulu表里的mulu_id
news_title   (varchar(300))   新闻标题
.....
.....

mulu表内容如下:
mulu_name     mulu_id     mulu_fid  
  ===========================
  '首页新闻 '         1               0  
  '心情故事 '         2               1  
  '网友推荐 '         3               1  
  '游戏相关 '         4               3  
  '其它 '                 5               3  
.....
.....

问题:
如何用sql语句把 '首页新闻 '分类及它的子分类下的所有新闻读出来?

不知道我说清楚没有

提示:最好不要用   SELECT     *   FROM   news   where   mulu_id   in   (....)   这样的语句
因为分类的子分类有可能太多,这样性能可能不好
求别的解决方法


------解决方案--------------------
try


Select A.* From news A Inner Join mulu B On A.mulu_id = B.mulu_id Where B.mulu_name = '首页新闻 '
Union All
Select A.* From news A Inner Join mulu B On A.mulu_id = B.mulu_id Inner Join mulu C On B.mulu_fid = C.mulu_id Where C.mulu_name = '首页新闻 '
------解决方案--------------------
up
------解决方案--------------------
〉〉我会把整张表都拿到DataTable里去处理,那个效率可快多了

上万客户并发,你的服务器就走掉了
------解决方案--------------------
用游标你的服务器基本死定了,因为它是一条条查下来的,

而楼主这个要求又是要递归查询,应该说是不可能性能好的

一般的做法是表里再加一个字段(以0,1组成),表示出层次关系,这样查询的效果会好的多
------解决方案--------------------
create function func_child
(
@id char(10)
)returns @tb (id char(10),level int)
as
begin
declare @level int
set @level = 1

insert into @tb
select @id,@level

while @@rowcount > 0
begin
set @level = @level + 1
insert into @tb
select a.mulu_id,@level from mulu a,@tb b
where a.mulu_fid = b.id and b.level = @level - 1
end

return
end

/*结果*/
select * from news a,dbo.func_child( '1 ') b
where a.mulu_id = b.id