CREATE TABLE #temp_knowledge ( knowledge_name NVARCHAR(MAX) , knowledge_id INT , p_knowledge_id INT ); INSERT INTO #temp_knowledge ( knowledge_name , knowledge_id , p_knowledge_id ) VALUES ( N'知识点1' , -- knowledge_name - nvarchar(max) 1 , -- knowledge_id - int 0 -- p_knowledge_id - int ); INSERT INTO #temp_knowledge ( knowledge_name , knowledge_id , p_knowledge_id ) VALUES ( N'知识点1.1' , -- knowledge_name - nvarchar(max) 2 , -- knowledge_id - int 1 -- p_knowledge_id - int ); INSERT INTO #temp_knowledge ( knowledge_name , knowledge_id , p_knowledge_id ) VALUES ( N'知识点1.2' , -- knowledge_name - nvarchar(max) 3 , -- knowledge_id - int 1 -- p_knowledge_id - int ); INSERT INTO #temp_knowledge ( knowledge_name , knowledge_id , p_knowledge_id ) VALUES ( N'知识点1.3' , -- knowledge_name - nvarchar(max) 4 , -- knowledge_id - int 1 -- p_knowledge_id - int ); INSERT INTO #temp_knowledge ( knowledge_name , knowledge_id , p_knowledge_id ) VALUES ( N'知识点1.1.1' , -- knowledge_name - nvarchar(max) 5 , -- knowledge_id - int 2 -- p_knowledge_id - int ); INSERT INTO #temp_knowledge ( knowledge_name , knowledge_id , p_knowledge_id ) VALUES ( N'知识点1.1.2' , -- knowledge_name - nvarchar(max) 6 , -- knowledge_id - int 2 -- p_knowledge_id - int ); INSERT INTO #temp_knowledge ( knowledge_name , knowledge_id , p_knowledge_id ) VALUES ( N'知识点2' , -- knowledge_name - nvarchar(max) 7 , -- knowledge_id - int 0 -- p_knowledge_id - int ); INSERT INTO #temp_knowledge ( knowledge_name , knowledge_id , p_knowledge_id ) VALUES ( N'知识点2.1' , -- knowledge_name - nvarchar(max) 8 , -- knowledge_id - int 7 -- p_knowledge_id - int ); INSERT INTO #temp_knowledge ( knowledge_name , knowledge_id , p_knowledge_id ) VALUES ( N'知识点2.2' , -- knowledge_name - nvarchar(max) 9 , -- knowledge_id - int 7 -- p_knowledge_id - int ); --查询该知识点id下的所以集合 DECLARE @knowledge_id INT = 1; WITH data AS ( SELECT * FROM #temp_knowledge tk WHERE knowledge_id = @knowledge_id UNION ALL SELECT tk.* FROM #temp_knowledge tk INNER JOIN data d ON tk.p_knowledge_id = d.knowledge_id ) SELECT * FROM data; DROP TABLE #temp_knowledge;
所有知识点集合:
SELECT * FROM #temp_knowledge
递归查询知识点id等于1下的所有子集:
--查询该知识点id下的所以集合 DECLARE @knowledge_id INT = 1; WITH data AS ( SELECT * FROM #temp_knowledge tk WHERE knowledge_id = @knowledge_id UNION ALL SELECT tk.* FROM #temp_knowledge tk INNER JOIN data d ON tk.p_knowledge_id = d.knowledge_id ) SELECT * FROM data;