2 个解决方案
#1
要想有详细说明,你也得把问题描述详细啊
#2
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[parentid] int,[comment] nvarchar(25))
Insert #T
select 1,0,N'原始评价1' union all
select 2,1,N'评价id1' union all
select 3,1,N'评价id1' union all
select 4,2,N'评价id2' union all
select 5,4,N'评价id4' union all
select 6,0,N'原始评价2' --这一级是不取的
Go
--测试数据结束
;WITH cte AS (
Select * from #T WHERE id=1 --查询id=1的所有子评价
UNION ALL
SELECT #T.* FROM #T JOIN cte ON cte.id = #T.parentid
)
SELECT * FROM cte
#1
要想有详细说明,你也得把问题描述详细啊
#2
--测试数据
if not object_id(N'Tempdb..#T') is null
drop table #T
Go
Create table #T([id] int,[parentid] int,[comment] nvarchar(25))
Insert #T
select 1,0,N'原始评价1' union all
select 2,1,N'评价id1' union all
select 3,1,N'评价id1' union all
select 4,2,N'评价id2' union all
select 5,4,N'评价id4' union all
select 6,0,N'原始评价2' --这一级是不取的
Go
--测试数据结束
;WITH cte AS (
Select * from #T WHERE id=1 --查询id=1的所有子评价
UNION ALL
SELECT #T.* FROM #T JOIN cte ON cte.id = #T.parentid
)
SELECT * FROM cte