How to get result from parent child table

前端 未结 4 1077
一个人的身影
一个人的身影 2021-01-22 14:44

Work on SQL-Server. My table structure is below

CREATE TABLE [dbo].[AgentInfo](
    [AgentID] [int] NOT NULL,
    [ParentID] [int] NULL,
 CONST         


        
4条回答
  •  醉话见心
    2021-01-22 15:12

    You can use a Common Table Expression to do this.

    The sql statement will then look like this:

    WITH [Parents]([AgentID], [ParentID], [BaseAgent])
    AS
    (
        SELECT 
          [AgentID],
          [ParentID],
          [AgentID] AS [BaseAgent]
        FROM [AgentInfo]
        WHERE [ParentID] = -1
        UNION ALL
        SELECT 
          [ai].[AgentID],
          [ai].[ParentID],
          [p].[BaseAgent]
        FROM [AgentInfo] [ai]
        INNER JOIN [Parents] [p] 
          ON [ai].[ParentID] = [p].[AgentID]
    )
    
    SELECT *
    FROM [Parents]
    ORDER BY 
      [BaseAgent] ASC,
      [AgentID] ASC
    

    But, the results are different from your desired output, since every Agent is only listed once. The output is:

    AGENTID     PARENTID    BASEAGENT
    1           -1          1
    3            1          1
    2           -1          2
    4            2          2
    

    The Fiddle is over here.

    And here is a nice post on working with hierarchies: What are the options for storing hierarchical data in a relational database?

提交回复
热议问题