SQL hiearchy select 两个表之间的查询

SQL hiearchy select query between two tables

我有 2 个 table(人员、部门)。

部门table看起来像这样:

ID (int)
Name (varchar)
ParentID (int)

人 table 喜欢这样:

Id (int)
FirstName (varchar)
SureName (varchar)
DepartmentId (int)
Manager (Bool)
Asistant (Bool)

我需要创建查询,select 具体人员的所有直接下属,即具体部门的经理。并且一查询其中 select 全部不仅是经理的直属下属。 每个部门有一名经理和一名助理。 manager == false 的人是直属下属,child depertment 的人是parent deprament 的下属。

我不知道如何在 SQL / LINQ 中创建此查询。

如有任何帮助,我将不胜感激!

示例: 部门

Id   Name          Parent
0    Department1   null
1    Department2   0
2    Department3   1

示例:

People
ID    Name      Department    DepartmentId    Manager    Asistant
1     Martin    Joshua            0             1           0
2     Ondra     Joshua2           0             0           0
3     Petr      Joshua3           0             0           0
4     Todd      Joshua3           1             1           0
5     Alex      Joshua3           1             0           0
6     Iva       Joshua3           1             0           0
7     Otto      Joshua3           2             1           0
8     Todd      Joshua3           2             0           0

例如,我需要 select id 为 0 的部门经理的所有(不仅是直接)下属,结果将如下所示:

2     Ondra     Joshua2           0             0           0
3     Petr      Joshua3           0             0           0
4     Todd      Joshua3           1             1           0
5     Alex      Joshua3           1             0           0
6     Iva       Joshua3           1             0           0
7     Otto      Joshua3           2             1           0
8     Todd      Joshua3           2             0           0

我不确定直接下属SQL 查询:

SELECT * FROM dbo.PeopleView WHERE DepartmentId = 162 AND Manager = 0; -- all direct s (162)

解决方案:

;WITH CTE AS
(
    SELECT 1 as EMPLEVEL, H1.Id, H1.ParentId, H1.Name FROM DepartmentView H1 WHERE Id = 6
    UNION ALL
    SELECT EMPLEVEL + 1, H2.Id, H2.ParentId, H2.Name FROM DepartmentView H2
    INNER JOIN CTE ON H2.ParentId = CTE.Id
)
SELECT DISTINCT P.Id, P.LastName,P.FirstName,P.DepartmentId,P.Manager,P.Assistant FROM CTE as T JOIN PeopleView as P on T.Id = P.DepartmentId;

除了你的第一个查询,就像@Andrew 的评论所说,递归查询可以帮助解决这个问题:

;WITH CTE
AS
(
SELECT ID,FirstName,SureName,DepartmentID,Manager,Assistant, 0 AS EMPLEVEL  FROM PEOPLE A  WHERE DepartmentId = 1 AND Manager = 0
UNION ALL 
SELECT B.ID,B.FirstName,B.SureName,B.DepartmentID,B.Manager,B.Assistant,EMPLEVEL +1 FROM PEOPLE B 
INNER JOIN DEPARTMENT D
ON B.DepartmentID = D.ID
INNER JOIN CTE 
ON D.ParentID = CTE.DepartmentID 
)
SELECT DISTINCT * FROM CTE 

要转换为 LINQ,您可以阅读此 post :P: Common Table Expression (CTE) in linq-to-sql?

希望对您有所帮助,此致。