2014-02-11 48 views
0

我有一個存儲父和子id的表,一個id可以有多個子類別,子類別可以有更多的類別,並且可以繼續)我有兩列「id」和「 parentid「來存儲該信息。SQL查詢中的子類別的計算級別

我需要填充第三列「級別」,解釋一個類別的層次結構級別,以便所有沒有子級的類別將具有級別= 1 ,從父類別繼承的子類別將具有級別= 2同樣所有子類別誰從子catogories繼承了進一步從主父類繼承將有等級= 3 ......而這將遵循

我如何填寫「等級」欄這裏

+0

看看這個巨大的假設http://blogs.msdn.com/b/simonince/archive/2007/10/17/hierarchies-with-common-table-expressions.aspx – Miller

回答

0

讓您使用MS SQL SERVER,你可以使用自參照(或遞歸)CTE的

;WITH CTE (id, p_id, level) 
AS 
(SELECT s.id, null,1 
    FROM table1 s 
    where parent_id is null 

    UNION ALL 

SELECT s.id,parent_id,m.level + 1 
    FROM CTE m 
    JOIN table1 s on m.id = s.parent_id 
) 
update table1 set level = c.level 
from cte c 
where table1.id = c.id; 
0

就像你描述它:首先更新所有記錄沒有孩子的記錄獲得1級,然後他們的父母獲得2級等等。因爲你沒有聲明DBMS既沒有語言Ë要使用,下面包含了一些僞代碼:

<declare and initialize a variable "@lvl" to 1> 

-- SQL: 
update category set level = 1 
where not exists(select 1 
        from category as parent 
        where catergory.parentId = parent.id) 

<while the last update updated some rows> 
    -- SQL: 
    update category set level = @lvl + 1 
    where exists(select 1 
        from category as child 
        where child.parentId = category.id 
        and child.level = @lvl) 
    <increment lvl by 1> 
<end of while loop>