【问题标题】:fetching tree structured data from postgresql从 postgresql 获取树结构数据
【发布时间】:2016-08-01 14:39:50
【问题描述】:

我正在弄清楚哪种方法是获取树状结构数据的有效方法

我有一张这样的桌子

表:food_categories

----------------------------------------------------------
| id     | parent       | category_name                  |
----------------------------------------------------------
| 1        0              Food                           |
| 2        1              Veg Items                      |
| 3        1              Non Veg Items                  |
| 4        2              Carrots                        |
| 5        2              Greens                         |
| 6        2              Milk                           |
| 7        3              Poultry                        |
| 8        3              Seafood                        |
| 9        7              Chicken                        |
| 10       8              Fish                           |
| 11       8              Prawns                         |
----------------------------------------------------------

树形结构的深度在这里不限,可以到任意层次

我想像下面这样获取这些

array(Food'=>array( 'Veg Items'=>array('carrots'=>array(),'Greens'=>array(),'Milk'=>array()),
                    'Non Veg Items'=>array(
                                            'Poultry'=>array('Chicken'=>array()),
                                            'Seafood'=>array('Fish'=>array(),'Prawns'=>array())
                                            )
                                    )
)

这样可以获取这种结构化数组吗?

我正在使用 postgresql,但我在这方面不是很方便,在 SO 和其他解释类似概念的文章中阅读了很多问题,但我无法准确理解。

感谢您的帮助。

【问题讨论】:

标签: php database postgresql


【解决方案1】:

在 Postgres 中,您可以使用递归 CTE 来做到这一点:

WITH RECURISVE recCTE AS
(
    --Recursive seed
    SELECT
        parent,
        id as child,
        0 as depth
        parent || '>' || id as path
    FROM
        food_categories
    WHERE parent = 0 --restricting to the top most node of your hierarchy

    UNION ALL

    --Recursive statement
    SELECT
        recCTE.child as Parent,
        fc.id as child,
        recCTE.depth + 1 as Depth,
        path || '>' || fc.id as path
    FROM
        recCTE 
        INNER JOIN food_categories fc 
            ON recCTE.child = fc.parent
    WHERE
        depth <=20 --Set this just in case we get into an infinite cycle
)

SELECT * FROM recCTE;

递归 CTE 包含三个部分:

  1. 递归种子,它是层次结构的起点。我猜你的情况是parent0
  2. 递归术语,它是递归 CTE 的一部分,它引用自身,连接到包含您的层次结构的表
  3. 告诉 Postgres 如何从 CTE 中进行选择的最终 SELECT。

这将取回层次结构中的每个节点、深度、父节点以及从根节点 0 到最低子节点的路径,无论深度如何(最多 20 个,因为我们将其卡在 WHERE 中) .

您可以将其与 json_aggrow_to_json 等结合使用,以将其转换为代码中更有用的对象,或者保持原样使用最后一个 SELECT 语句从中获取所需的位.如果您对这条路线感兴趣,可以查看this great explaination and example

【讨论】:

    猜你喜欢
    • 2022-06-13
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 2010-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    相关资源
    最近更新 更多