【发布时间】:2015-06-17 22:53:48
【问题描述】:
我有三张桌子:
Department(ID,name) ,
SubDepartment(parentID,childID) and
Department_Employees(idEmployee, idDepartment)
- 在“Department_Employees”表中,idDepartment 是外键链接的 到“部门”表的 ID。
- 在“SubDepartment”表中,parentID 和 childID 是外键,都链接到“Department”表的 ID。
一个Department(parent)可以有多个SubDepartments(children),而那些SubDepartments可以有自己的SubDepartments(children) 但 SubDepartment(child) 不能是其任何父部门的父级。 “idEmployee” 在表“Department_Employees”中是不同的(Employee 只能属于一个部门)。这些规则从前端覆盖。
我必须计算某个部门及其所有子部门中有多少员工(“idEmployee”)。我还必须计算某个部门中有多少子部门,包括所有孩子。
假设我有这样的东西:
1. MainDepartment(6 employees)
- ITSector(3 employees)
* Databases(4 employees)
* Programmers(2 employees)
- DeliverySector(4 employees)
我需要输出为 MainDepartment 有 4 个子部门和 19 名员工。
是否可以或建议在一个带有子查询的查询中执行此操作?我认为我需要为此进行某种递归,但我不知道如何编写它。
【问题讨论】:
-
但是部门代码和Iddepartment代码重叠?可能是 iddepartment =1 和 childdepartment =1?
-
它确实重叠,但这种情况以及循环情况都在前面排序。之所以有三个表而不是仅将部门链接到自身,是因为子部门表中还有字段日期,因为我需要能够跟踪孩子切换父母的历史。
-
我发布了一个解决方案,您必须在 subdp 表中插入一个列名。他们不能重叠,怎么能分辨出1的儿子谁是他的父亲?您必须更改某些内容,可能将所有内容放在同一个表中,并且 parentid=-1 用于主要部门。如果重叠,下面的查询会给出错误的结果。