2010-07-05 52 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进行处理;也许这里有人会为这种情况提供适当的代码。