SELECT and list children and parent

后端 未结 2 1276
梦谈多话
梦谈多话 2021-01-24 03:12

I need a SQL query for the following COMPLEX task...

I need to to select from a column named parent_id. If a row has 0 for parent_id it means t

2条回答
  •  -上瘾入骨i
    2021-01-24 03:49

    Using FOR XML EXPLICIT you can get a hierarchical list.

    Try this:

    SELECT 
     1 Tag,
     null Parent,
     '' [root!1!name],
     null [category!2!id],
     null [category!2!name],
     null [rule!3!id],
     null [rule!3!name]
    
    UNION ALL 
    
    SELECT DISTINCT 
     2 Tag,
     1 Parent,
     null,
     rule_id [category!2!id],
     rule_title [category!2!name],
     null [rule!3!id],
     null [rule!3!name]
    FROM rules
    WHERE parent_id = 0 and rule_type = 'cat'
    
    UNION ALL 
    
    SELECT  
     3 Tag,
     2 Parent,
     null,
     parent_id [category!2!id],
     null [category!2!name],
     rule_id [rule!3!id],
     rule_title [rule!3!name]
    FROM rules
    WHERE parent_id > 0 and rule_type = 'rule'
    
    FOR XML EXPLICIT
    

    For more information visit http://msdn.microsoft.com/en-us/library/ms189068.aspx

提交回复
热议问题