开发者

How to find all the descendants with SQL?

开发者 https://www.devze.com 2023-04-09 23:44 出处:网络
Each entity can have one parent. I need to find all the descendants of 开发者_Python百科a given entity.

Each entity can have one parent. I need to find all the descendants of 开发者_Python百科a given entity.

Is it possible with just SQL?

I can only think in terms of a script, and it won't be as fast as sql alone.

I'm using PHP and MS SQL Server 2005, and doctrine 2 DBAL


For SQL Server 2005+, you can use a recursive CTE.

WITH cteRecursion AS (
    SELECT PrimaryKey, 1 AS Level
        FROM YourTable
        WHERE PrimaryKey = @GivenEntity
    UNION ALL
    SELECT t.PrimaryKey, c.Level+1
        FROM YourTable t
            INNER JOIN cteRecursion c
                ON t.ParentKey = c.PrimaryKey
)
SELECT PrimaryKey, Level
    FROM cteRecursion
    ORDER BY Level, PrimaryKey;


PHP will run one SQL statement at a time so you will need to create this list in a loop. A good alternative is to use nested sets.

0

精彩评论

暂无评论...
验证码 换一张
取 消