mysql 如果层次是固定的一层或者几层可以使用 union all +join 层次不固定只能使用存储过程去写递归了
declare @str varchar(4000) set @str='' select @str=@str+' '+ cast([id] as varchar(20)) from T_1 where parentId=52 select @str 结果:‘ 54 55 56 57 61‘ 我的数据库时sql server 不知道可不可以,也不知道是不是你想要的结果
我的数据库是sql server 的,结果应该不会错,可能效率不是很高,如果那个表中少与1w条记录应该没有什么问题--建表 create table t_2( [id] int,[parentId] int ) --添加数据 insert into t_2 select 52,-1 union all select 53,0 union all select 54,52 union all select 55,52 union all select 56,54 union all select 57,55 union all select 61,56 ------------------sql开始 declare @parentId int set @parentId=52--传入的参数值 declare @temp_1 table([ID] [int] IDENTITY(1,1),a_id int,[parentId] int)--临时表1 declare @temp_2 table([id] int)--临时表2insert into @temp_2 values(@parentId)--给临时表2添加最开始的数据 insert into @temp_1([a_id],[parentId])--把所有数据添加到临时表2中 select id,parentId from t_2declare @index int,@rowCut int--声明循环参数 set @index=1--循环初始值 select @rowCut=count(1) from @temp_1--循环结束值 while @index<=@rowCut--循环条件 begin insert into @temp_2([id]) select a_id from @temp_2 aa --如果不是重复的,并且不是空的就添加进去 right join ( --这里面的sql是求出这些parentId 所对应所有的id select a_id from @temp_1 a right join @temp_2 b on a.parentId=b.id )bb on aa.id =bb.a_id where aa.id is null and a_id is not null set @index=@index+1--循环步长 end delete from @temp_2 where id=@parentId--删除最开始设置的值 select * from @temp_2--查询 --------------------------sql结束 结果是
union all +join
层次不固定只能使用存储过程去写递归了
set @str=''
select @str=@str+' '+ cast([id] as varchar(20)) from T_1 where parentId=52
select @str
结果:‘ 54 55 56 57 61‘
我的数据库时sql server 不知道可不可以,也不知道是不是你想要的结果
create table t_2( [id] int,[parentId] int )
--添加数据
insert into t_2
select 52,-1
union all
select 53,0
union all
select 54,52
union all
select 55,52
union all
select 56,54
union all
select 57,55
union all
select 61,56
------------------sql开始
declare @parentId int
set @parentId=52--传入的参数值
declare @temp_1 table([ID] [int] IDENTITY(1,1),a_id int,[parentId] int)--临时表1
declare @temp_2 table([id] int)--临时表2insert into @temp_2 values(@parentId)--给临时表2添加最开始的数据
insert into @temp_1([a_id],[parentId])--把所有数据添加到临时表2中
select id,parentId from t_2declare @index int,@rowCut int--声明循环参数
set @index=1--循环初始值
select @rowCut=count(1) from @temp_1--循环结束值
while @index<=@rowCut--循环条件
begin
insert into @temp_2([id])
select a_id from @temp_2 aa --如果不是重复的,并且不是空的就添加进去
right join
(
--这里面的sql是求出这些parentId 所对应所有的id
select a_id from @temp_1 a
right join @temp_2 b on a.parentId=b.id
)bb
on aa.id =bb.a_id
where aa.id is null and a_id is not null set @index=@index+1--循环步长
end
delete from @temp_2 where id=@parentId--删除最开始设置的值
select * from @temp_2--查询
--------------------------sql结束
结果是