sql - 复杂的 TSQL order by 子句

标签 sql sql-server-2005 tsql

是否可以制作一个 ORDER BY 子句来确保两个字段(均为 INT 类型)的以下标准,称为 childparent分别为本例。

  • parent引用 child ,但可以为空。
  • 一个 parent 可以有多个 child ;一个 child 只有一个 parent 。
  • child 不能是自己的 parent 。
  • 必须至少存在一个没有 parent 的 child 。
  • 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
    

    对于在父列中定义非空值的每一行,该值已经存在于子列中。

    最佳答案

    您可以使用递归 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
    

    关于sql - 复杂的 TSQL order by 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3179010/

    相关文章:

    SQL Server (TSQL) - 是否可以并行执行语句?

    sql-server - 如何避免在 SQL 中存储像 <option/> 这样的 XML <option></option>?

    sql - 如何返回当天写的最新行?

    c# - 如何使用存储过程在 LINQ to SQL 中使用事务?

    sql - 简单的日期时间sql查询

    tsql - TSQL 中的左修剪换行符

    c# - SQL 注入(inject),使用参数化查询

    php - 用php编辑表格的行

    php - Yii2 条件连接两个外键到同一个表

    c# - SQL 2005 最佳 "Paging"