大家好!
有表A,有如下字段:TypeId(分类编号),TypeName(分类名称),ParentId(父类编号,如果是顶级分类则为0)
我现在要多查出一列:所属父类名称
如:
编号 名称 所属父类
1 分类1 顶级分类
2 分类2 顶级分类
3 分类11 分类1请教这SQL语句怎么写效率最好?谢谢!
有表A,有如下字段:TypeId(分类编号),TypeName(分类名称),ParentId(父类编号,如果是顶级分类则为0)
我现在要多查出一列:所属父类名称
如:
编号 名称 所属父类
1 分类1 顶级分类
2 分类2 顶级分类
3 分类11 分类1请教这SQL语句怎么写效率最好?谢谢!
FROM [表名] AS A
LEFT JOIN [表名] AS B
ON A.[ParentId]=B.[TypeId]
insert into #
select 1,0,'1级1' union all
select 2,0,'1级2' union all
select 3,1,'2级1_1' union all
select 4,2,'2级2_1' union all
select 5,1,'2级1_2' union all
select 6,2,'2级2_2'select a.id,a.pid,a.nm,b.nm as pnm from # a,# b
where a.pid=b.id
/*
id pid nm pnm
3 1 2级1_1 1级1
4 2 2级2_1 1级2
5 1 2级1_2 1级1
6 2 2级2_2 1级2
*/
;with cte as
(
select * from # where id=3
union all
select a.* from # a join cte b on a.id=b.pid
)
select * from cte
/*
id pid nm
3 1 2级1_1
1 0 1级1
*/
http://topic.csdn.net/u/20080313/18/db635e25-ea62-4200-b4be-83c216c66ae9.html?1658937245
假设以下商品表结构(树形): --食品
--水果
--香蕉
--苹果
--蔬菜
--青菜
... declare @TreeTable (ID smallint,PID smallint,name)
insert @TreeTable
select 1,0,'食品'
union all
select 2,1,'水果'
union all
select 3,1,'蔬菜'
union all
select 4,2,'香蕉'
union all
select 5,2,'苹果'
union all
select 6,3,'青菜' 怎样能够得到下列的一个表:
ID PID Name Path
1 0 食品 食品
2 1 水果 食品,水果
3 1 蔬菜 食品,蔬菜
4 2 香蕉 食品,水果,香蕉
5 2 苹果 食品,水果,苹果
6 3 青菜 食品,蔬菜,青菜 相当于将一个树状的表,如果在后面产生一列体现当前节点的路径的字符串,如果能够控制显示的树的层数那就更好了。请各位大侠帮我看下。谢谢。
--------------------------------------------------------------------------------------------
create function f_pid(@id int) returns varchar(100)
as
begin
declare @re_str as varchar(100)
set @re_str = ''
select @re_str = name from tb where id = @id
while exists (select 1 from tb where id = @id and pid <> 0)
begin
select @id = b.id , @re_str = b.name + ',' + @re_str from tb a , tb b where a.id = @id and a.pid = b.id
end
return @re_str
end
gocreate table tb (id int , pid int , name nvarchar(20))
insert into tb values(1 , 0 , '食品')
insert into tb values(2 , 1 , '水果')
insert into tb values(3 , 1 , '蔬菜')
insert into tb values(4 , 2 , '香蕉')
insert into tb values(5 , 2 , '苹果')
insert into tb values(6 , 3 , '青菜')
goselect * , dbo.f_pid(id) 路径 from tbdrop function f_piddrop table tb/*
id pid name 路径
--- --- ----- ---------------
1 0 食品 食品
2 1 水果 食品,水果
3 1 蔬菜 食品,蔬菜
4 2 香蕉 食品,水果,香蕉
5 2 苹果 食品,水果,苹果
6 3 青菜 食品,蔬菜,青菜(所影响的行数为 6 行)
*/