如何在sql中创建一个树,何时能以这种方式获取数据?
category_id |category_parent |category_code |category_name
------------|----------------|-------------------|---------------------
70 |0 |Vege |Vegetable
71 |0 |Frui |Fruit
72 |0 |Fish |Fishery
73 |71 |Butc |Butchery
74 |72 |Poul |Poultry
75 |73 |Dair |Dairy
76 |75 |Deli |Delicatessen
77 |75 |Frofod |Frozen Food
78 |76 |Foserv |Food Service
79 |77 |Pla Flo |Plant & Flower
80 |79 |ConFresh |Consightment Fresh
81 |79 |Café |Café
答案 0 :(得分:0)
您想要查找的是公用表表达式(CTE)。 Here是CTE的一个很好的例子。
所以你想做的事情看起来像那样:
WITH Tree(child_category_id, child_name, child_category, parent_id, Parents)
AS
(
--1st level rows (parent)
SELECT category_id, category_name, category_code, category_parent, CAST('' AS VARCHAR(MAX))
FROM YourTable AS FirtGeneration
WHERE category_parent = 0
UNION ALL
--children
SELECT NextGeneration.category_id, NextGeneration.category_name, NextGeneration.category_code, Parent.child_category_id,
CAST(CASE WHEN Parent.Parents = ''
THEN(CAST(NextGeneration.category_parent AS VARCHAR(MAX)))
ELSE(Parent.Parents + '.' + CAST(NextGeneration.category_parent AS VARCHAR(MAX)))
END AS VARCHAR(MAX))
FROM YourTable AS NextGeneration
INNER JOIN Tree AS Parent ON NextGeneration.category_id = Parent.child_category_id
)
SELECT *
FROM Tree
--not needed here because you wont do that many recursions
--OPTION(MAXRECURSION 32767)