簡體   English   中英

從自引用表中以父子順序檢索父子關系的 SQL

[英]SQL to retrieve parent-child relationship in parent-child order, from a self referencing table

我使用以下查詢從自引用父級的表中檢索父子關系數據。

    -- go down the hierarchy and get the childs
    WITH ChildLocations(LocationId, FkParentLocationId, [Level]) 
        AS 
        (
            (
                -- Start CTE off by selecting the home location of the user
                SELECT l.LocationId, l.FkParentLocationId, 0 as [Level]
                FROM   Location l
                WHERE  l.LocationId = @locationId
            )
            UNION ALL 
            -- Recursively add locations that are children of records already found in previous iterations.
            SELECT l2.LocationId, l2.FkParentLocationId, [Level] + 1
            FROM   ChildLocations tmp
                   INNER JOIN Location l2
                        ON  l2.FkParentLocationId = tmp.LocationId
        )
    INSERT INTO @tmp
    SELECT * from ChildLocations;

該表具有以下字段:LocationId、FkParentLocationId、FkLocationTypeId 等...

這工作正常,但我想如何檢索它如下:

 Parent 1 Child 1 Child 2 Child 21 Child 3 Child 31 Parent 2 Child 4 Child 5 Child 6

目前給出的是:

 Parent 1 Parent 2 Child 1 Child 2 Child 3 Child 4 etc....

如何修改上述內容以按我想要的順序獲取它。

附加一個“訂單”字段怎么樣? 這可能是一種方法:

WITH ChildLocations(LocationId, FkParentLocationId, [Level]) 
    AS 
    (
        (
            -- Start CTE off by selecting the home location of the user
            SELECT l.LocationId, l.FkParentLocationId, 0 as [Level],
                   cast( str( l.locationId ) as varchar(max) ) as orderField
            FROM   Location l
            WHERE  l.LocationId = @locationId
        )
        UNION ALL 
        -- Recursively add locations that are children ...
        SELECT l2.LocationId, l2.FkParentLocationId, [Level] + 1,
               tmp.orderField + '-' + 
               str(tmp.locationId) as orderField
        FROM   ChildLocations tmp
               INNER JOIN Location l2
                    ON  l2.FkParentLocationId = tmp.LocationId
    )
SELECT * from ChildLocations order by orderField;

記住比Order by中的Insert是不允許的。

看一個樣本

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM