postgresql WITH RECURSIVE查询获取类别和子类别

时间:2016-05-11 20:18:29

标签: sql postgresql join hierarchical-data

我有一张表格如下

enter image description here

使用WITH RECURSIVE语句,我可以获得表格的深度

:

我应该如何更改查询,以便我可以获得如下输出(直到树的第n级)?

enter image description here

我打算使用上面的结果生成如下的站点地图:

enter image description here

我目前正在尝试使用WITH RECURSIVE语句使用LEFT OUTER JOIN,但我无法找到怎么办?有人可以指导一下吗?

1 个答案:

答案 0 :(得分:1)

对于您描述的输出格式,我不会进行递归查询。递归查询会生成您需要透视以获取格式的行。在透视查询中,您需要指定您将拥有哪些列。总而言之,这将成为一个长查询,对于只有4或5列的输出,以下内容将更加简单:

SELECT    c0.name  AS root_name,
          c1.name  AS down1_name,
          c2.name  AS down2_name,
          c3.name  AS down3_name,
          c4.name  AS down4_name,
          c5.name  AS down5_name
FROM      category c0
LEFT JOIN category c1 ON c1.parentid = c0.id
LEFT JOIN category c2 ON c2.parentid = c1.id
LEFT JOIN category c3 ON c3.parentid = c2.id
LEFT JOIN category c4 ON c4.parentid = c3.id
LEFT JOIN category c5 ON c5.parentid = c4.id
WHERE     c0.parentid IS NULL
ORDER BY  c0.id, c1.id, c2.id, c3.id, c4.id, c5.id