簡體   English   中英

SQL查詢3級樹?

[英]Sql query for 3 level tree?

我有桌子,我要3棵樹。

Node
Id     ParentId     Name
 1       -1       Test 1
 2       -1       Test 2
 3        1       Test 1.1
 4        1       Test 1.2
 5        3       Test 1.1.1
 6        3       Test 1.1.2
 7        5       Test 1.1.1.1

如果我過濾了ParentId = -1我想獲取ParentId = -1行和children's +2 lvl。

如果我filtered Id = 2我想獲得Id = 2行和children's +2 lvl。

UPDATE

我使用MS SQL Server 2008,實體框架6.1.3。 我了解,我可以使用3個選擇。 但是我在尋找有效的方法

您可以使用遞歸SQL在SQL Server中執行此操作。

WITH recCTE (childID, parentID, Name, Depth) Assuming
(
    Select
        yourTable.id as childid,
        yourTable.parentID,
        CAST('Test ' + yourTable.id as varchar(20)) as Name
        0 as Depth
    FROM
        yourTable
    WHERE
        parentID = -1

    UNION ALL

    Select
        yourTable.id as childID,
        yourTable.ParentID as ParentID,
        recCTE.path + '.' + yourTable.id AS Name
        recCTE.depth + 1 as Depth
    FROM
        recCTE
        INNER JOIN yourTable on
        recCTE.childID = yourTable.parentID
    Where
        recCTE.Depth + 1 <= 2
)

SELECT * FROM recCTE;

UNION頂部CTE內的位是您對遞歸sql的種子查詢。 這是您開始遞歸查找的地方。 您想從parentID = -1開始,所以它在WHERE語句中。

CTE內部UNION下方的位是遞歸項。 這將遞歸CTE重新結合起來,並從表中引入更多數據。 將表中的ID與遞歸結果集中的childID連接起來。

遞歸術語是我們進行測試以了解我們已經深入的地方。 如果CTE + 1的深度小於或等於2,則我們停止將子級添加到循環中,從而結束層次結構中該特定分支的循環。

CTE下方的​​最后一點只是運行CTE的部分,因此您可以獲得結果。

起初,這些遞歸查詢令人感到困惑,但是花一些時間處理它們,您會發現它們有很多用途。 您還將發現,一旦將所有部分都擱置一旁,編寫它們就不會太困難。

暫無
暫無

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

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