2010-07-05 50 views
7

是否可以使用ORDER BY子句來確保兩個字段(都是INT類型)的以下標準,在本例中分別被稱爲childparent複雜的TSQL訂單子句

  1. parent參考child,但可以爲空。
  2. 父母可以有多個孩子;一個孩子只有一個父母。
  3. 小孩不能成爲自己的父母。
  4. 必須存在至少一個沒有父母的孩子。
  5. child的每個值必須出現在parent中的有序結果集中。

我在遇到困難點5

樣品無序數據:

child parent 
------------ 
1  NULL 
3  5 
4  2 
2  5 
5  NULL 

顯然既不ORDER BY a, bORDER BY b, a工作。事實上,我越想到它,我也不確定它甚至可以完成。鑑於限制,明顯的情況如:

child parent 
------------ 
1  2 
2  1 

是不允許的,因爲它違反了規則3和4(顯然是5)。

那麼,我正在努力實現的可能性,如果是的話,怎麼樣?平臺是SQL Server 2005中

更新:所需的排序順序爲樣本數據:

child parent 
------------ 
1  NULL 
5  NULL 
2  5 
3  5 
4  2 

對於每一行定義父列一個非空值,該值已經存在了int子列。

+0

你能表現出所需的順序樣本數據,好嗎?這將是一個幫助。 – 2010-07-05 11:21:11

+0

根據您的要求添加,Brian。 – 2010-07-05 12:16:53

回答

6

你可以使用遞歸CTE找到每個節點的「深度」,並命令由:

create table node (id int, parent int) 
insert into node values (1, null) 
insert into node values (2, 5) 
insert into node values (3, 5) 
insert into node values (4, 2) 
insert into node values (5, null) 
insert into node values (6, 4); 

with node_cte (id, depth) as (
    select id, 0 from node where parent is null 
    union all 
    select node.id, node_cte.depth + 1 
    from node join node_cte on node.parent = node_cte.id  
) 

select node.* 
from node 
join node_cte on node_cte.id=node.id 
order by node_cte.depth asc 
+1

啊,遞歸的CTE。他們有什麼不能做的嗎? – 2010-07-05 12:25:32

1

您將無法使用'ORDER BY'子句執行此操作,因爲要求5指定該訂單對數據層次結構敏感。在SQL Server 2005中,層次數據通常使用遞歸CTE進行處理;也許這裏有人會爲這種情況提供適當的代碼。