从2个表创建分层数据

时间:2019-07-18 21:30:10

标签: sql sql-server hierarchy

我有两个这样的表:

ProdId ProdName
1      Mike
2      Carol
3      John
4      Marc

OrdId OrdName ProdId
100     Pizza   1
101     Subs    1
102     Calzone 2
102     Sausage 2
102     Beef    2
105     Pork    4
106     Coke    4

我需要一个查询来填充这样的结果。层次结构应该是父级及其子级,然后是父级,然后是子级。

MarkerId  MarkerName MarkerParentId
1         Mike       NULL
100       Pizza      1
101       Subs       1
2         Carol      NULL
102       Calzone    2
103       Sausage    2
104       Beef       2
3         John       NULL
4         Marc       NULL
105       Pork       4
106       Coke       4

请帮助。谢谢。

1 个答案:

答案 0 :(得分:1)

与递归无关。基本上,UNION

可以满足您的需求
SELECT ProdId as MarkerId, ProdName as MarkerName, NULL as MarkerParentId from t1
UNION ALL 
SELECT OrdId as MarkerId, OrdName as MarkerName, ProdId MarkerParentId from t2
ORDER BY MarkerId, MarkerParentId