问一个多级分类查询的问题?

kerer 2005-10-10 04:59:25
最近在做一个图书管理系统,涉及到图书分类的问题。
类别表是book_Catalogs,结构如下
(
fId int, -- 类别编号
fName nvarchar(20), -- 类别名称
fDescription nvarchar(50), -- 类别描述
fParentId int, -- 父级类别
fIsLeaf bit -- 是否叶子类(图书只能归属于叶子类)
)
类别图书关系表是book_CatalogBooks,结构如下
(
fCatalogId int, -- 类别编号
fBookId int, -- 图书编号
)

现在我想通过book_CatalogBooks表查找某一个类别下的所有图书。无论指定哪个类别,都能找到该类别下的所有图书,如果该分类下有子分类,还有包括该类所有子类下的图书。希望能用一个SELECT语句搞定。
...全文
122 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
zxbyhcsdn 2005-10-10
  • 打赏
  • 举报
回复
感觉这个有点的规的样子!!
子陌红尘 2005-10-10
  • 打赏
  • 举报
回复
一条SQL恐怕有些困难,借助UDF:
--------------------------------------------------------------------------------
--创建用户定义函数
declare function f_getchlid(@fId int)
returns @t table(fId int,fName nvarchar(20),fParentId int,fIsLeaf bit,level int)
as
begin
declare @level int
set @level = 1

insert into @t
select
fId,fName,fParentId,fIsLeaf,@level
from
book_Catalogs
where
fId=@fId

while @@rowcount!=0 and exists(select * from @t where level=@level and fIsLeaf=0)
begin
insert into @t
select
a.fId,a.fName,a.fParentId,a.fIsLeaf,@level+1
from
book_Catalogs a,@t b
where
b.fId=a.fParentId
and
b.level=@level

set @level = @level+1
end

return
end
go


--执行查询
declare @fid int
set @fid = 1

select
*
from
book_CatalogBooks
where
fCatalogId in(select a.fId from dbo.f_getchlid(@fid) a where a.fIsLeaf=1)
zxbyhcsdn 2005-10-10
  • 打赏
  • 举报
回复
用动态Sql看看!!
happygong 2005-10-10
  • 打赏
  • 举报
回复
这种树状结构的实现方法不太好
应该使用NodeCode的方法
比如规定以4个字符为单位
0001(父节点)
--00010001(子节点)
----000100010001(孙节点)
----000100010002
--00010002
--00010003
这样记录的树状结构可以使用where nodecode like '00010001%'获得所有00010001下面的子节点
但是有缺点就是同一级最多有10000个,如果还需要更多,可以选择已6个字符为单位

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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