使用多个表SQL Server创建层次结构递归

时间:2016-09-08 10:04:57

标签: sql sql-server parent-child recursive-query

我想创建一个显示员工在经理下面的查询 在SQL上使用5个表 这是我的数据库的例子。

<script src="https://code.jquery.com/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<div id="client-paginator">
  <ul class="pagination">

    <li><a id="pag-123">123</a>
    </li>
    <li><a id="pag-a">A</a>
    </li>
    <li><a id="pag-b">B</a>
    </li>
    <li><a id="pag-c">C</a>
    </li>
    <li><a id="pag-d">D</a>
    </li>
    <li><a id="pag-e">E</a>
    </li>
    <li><a id="pag-f">F</a>
    </li>
    <li class=""><a id="pag-g">G</a>
    </li>
    <li><a id="pag-h">H</a>
    </li>
    <li><a id="pag-i">I</a>
    </li>
    <li><a id="pag-j">J</a>
    </li>
    <li><a id="pag-k">K</a>
    </li>
    <li><a id="pag-l">L</a>
    </li>
    <li class="active"><a id="pag-m">M</a>
    </li>
    <li><a id="pag-n">N</a>
    </li>
    <li class=""><a id="pag-o">O</a>
    </li>
    <li class=""><a id="pag-P">P</a>
    </li>
    <li><a id="pag-q">Q</a>
    </li>
    <li><a id="pag-r">R</a>
    </li>
    <li><a id="pag-s">S</a>
    </li>
    <li><a id="pag-t">T</a>
    </li>
    <li class=""><a id="pag-u">U</a>
    </li>
    <li><a id="pag-v">V</a>
    </li>
    <li><a id="pag-w">W</a>
    </li>
    <li><a id="pag-x">X</a>
    </li>
    <li><a id="pag-y">Y</a>
    </li>
    <li><a id="pag-z">Z</a>
    </li>
    <li class=""><a id="pag-ä">Ä</a>
    </li>
    <li class=""><a id="pag-ö">Ö</a>
    </li>
    <li class=""><a id="pag-ü">Ü</a>
    </li>
  </ul>

</div>

当我在Query(WHERE EmpId = 1)上输入id时,它显示谁是低于id 1的员工,因此它将是EmpId 5然后是4.当EmpId = 2时,孩子是Empid 3-1-5 -4。
我是怎么做到的?

1 个答案:

答案 0 :(得分:0)

不确定是否理解了整个问题,但你可以尝试一下。

Declare @empid as int;
SET @empid = 1;

With A as 
(
    Select id as Subord_role
    from role
    WHERE role.parent = (Select deptrole.idrole
                            FROM Employee
                                INNER JOIN deptrole ON deptrole.id = Employee.id
                            WHERE Employee.id = @empid)
    UNION ALL

    Select Role.id
    from deptrole 
        INNER JOIN Role ON deptrole.idrole = Role.id
        INNER JOIN A ON A.Subord_role = Role.parent
    Where deptrole.iddept = (Select deptrole.iddept
                            FROM Employee
                                INNER JOIN deptrole ON deptrole.id = Employee.id
                            WHERE Employee.id = @empid)
)

Select Employee.id
FROM Employee
    INNER JOIN deptrole ON deptrole.id = Employee.id
    INNER JOIN Role ON role.id = deptrole.idrole 
    INNER JOIN A ON A.Subord_role = Role.id