2014-06-10 110 views
1

我在這個問題上停留了一段時間。遞歸查詢SQL Server

我有一個表稱爲範疇,看起來像這樣:

number, name, parent 
1  , Fruit, null 
2  , Apples, 1 
3  , Golden Apples, 2 
4  , Pineapples, 1 

現在,我該如何選擇主類別和其子類別和如果存在的話,它們的子類。

我必須在PHP輸出這樣的:

<div>Fruit 
    <div>Apples 
      <div>Golden Apples</div> 
    </div> 
    <div>Pineapples</div> 
</div> 

在理論上沒有已知的結束或子類別的數量,你可以有。我一直在努力解決這個問題。

可以用循環完成此操作,然後運行查詢以再次選擇其子類別,但這在數據庫端會非常耗費資源。

我希望有人能幫助我這個。

+0

你應該看看這裏:http://technet.microsoft.com/en-us/library/ms186243%28v=sql.105%29.aspx – PeterRing

回答

0

理想的方法是規範化您的數據。有一個類別表和一個表,其中包含每個類別的成員。然後,您可以在表格之間進行簡單的左連接,以獲得您要查找的內容。既然你沒有這些,你將需要從主表中選擇,然後使用別名在同一個表上進行左連接。

這樣的事情會起作用。

選擇號碼,從類別名稱,其中母公司爲NULL 左連接類別爲Items上Items.Parent = Category.number

0

嘗試使用遞歸CTE這樣的:

--this is just an old example I've used before, but it kind of matches your table 
--go through a nested table supervisor - user table and display the chain 
DECLARE @Contacts table (id int, first_name varchar(10), reports_to_id int) 
INSERT @Contacts VALUES (1,'Jerome', NULL) -- tree is as follows: 
INSERT @Contacts VALUES (2,'Joe' ,'1')  --      1-Jerome 
INSERT @Contacts VALUES (3,'Paul' ,'2')  --     /  \ 
INSERT @Contacts VALUES (4,'Jack' ,'3')  --    2-Joe   9-Bill 
INSERT @Contacts VALUES (5,'Daniel','3')  --   /  \    \ 
INSERT @Contacts VALUES (6,'David' ,'2')  --  3-Paul   6-David  10-Sam 
INSERT @Contacts VALUES (7,'Ian' ,'6')  -- / \   / \ 
INSERT @Contacts VALUES (8,'Helen' ,'6')  -- 4-Jack 5-Daniel 7-Ian 8-Helen 
INSERT @Contacts VALUES (9,'Bill ' ,'1')  -- 
INSERT @Contacts VALUES (10,'Sam' ,'9')  -- 

DECLARE @Root_id int 

--get complete tree--------------------------------------------------- 
SET @Root_id=null 
PRINT '@Root_id='+COALESCE(''''+CONVERT(varchar(5),@Root_id)+'''','null') 
;WITH StaffTree AS 
(
    SELECT 
     c.id, c.first_name, c.reports_to_id, c.reports_to_id as Manager_id, cc.first_name AS Manager_first_name, 1 AS LevelOf 
     FROM @Contacts     c 
      LEFT OUTER JOIN @Contacts cc ON c.reports_to_id=cc.id 
     WHERE [email protected]_id OR (@Root_id IS NULL AND c.reports_to_id IS NULL) 
    UNION ALL 
     SELECT 
      s.id, s.first_name, s.reports_to_id, t.id, t.first_name, t.LevelOf+1 
     FROM StaffTree   t 
      INNER JOIN @Contacts s ON t.id=s.reports_to_id 
    WHERE [email protected]_id OR @Root_id IS NULL OR t.LevelOf>1 
) 
SELECT * FROM StaffTree ORDER BY LevelOf,first_name 

OUTPUT:

@Root_id=null 
     id first_name reports_to_id Manager_id Manager_first_name  LevelOf 
----------- ---------- ------------- ----------- ------------------ ----------- 
      1 Jerome    NULL  NULL NULL       1 
      9 Bill     1   1 Jerome      2 
      2 Joe     1   1 Jerome      2 
      6 David     2   2 Joe       3 
      3 Paul     2   2 Joe       3 
     10 Sam     9   9 Bill       3 
      5 Daniel     3   3 Paul       4 
      8 Helen     6   6 David      4 
      7 Ian     6   6 David      4 
      4 Jack     3   3 Paul       4 

(10 row(s) affected) 

我想你可以循環使用PHP中的結果集並構建你的DIV。