简体   繁体   English

如何编写这个递归 MySQL 程序?

[英]How do I write this recursive MySQL procedure?

I have a MySQL database which contains 2 (relevant) tables: Staff, Supervisors.我有一个 MySQL 数据库,其中包含 2 个(相关)表:员工、主管。

Staff contains: StaffID, Name, CostCentre员工包含:员工 ID、姓名、成本中心

and Supervisors contains: InstanceID, StaffID, SupervisorID, Obsolete和 Supervisors 包含:InstanceID、StaffID、SupervisorID、Obsolete

The Staff table contains all staff in the company, and the Supervisors table links one StaffID (StaffID) to another StaffID (SupervisorID). Staff 表包含公司中的所有员工,Supervisors 表将一个 StaffID (StaffID) 链接到另一个 StaffID (SupervisorID)。 If we create a new relationship (ie staff A no longer reports to staff B, but instead to staff C), then we create a new record and set the original 'obsolete' flag to 'true'.如果我们创建一个新的关系(即员工 A 不再向员工 B 报告,而是向员工 C 报告),那么我们创建一个新记录并将原来的“过时”标志设置为“真”。

I have arranged it this way because the Supervisor:Subordinate relationships are subject to change, and are not guaranteed to be correct: We want to be able to change them and maintain an audit trail.我这样安排是因为主管:下属关系可能会发生变化,并且不能保证正确:我们希望能够更改它们并保持审计跟踪。

What I need to do is to get a recursive list of CostCentres.我需要做的是获取 CostCentres 的递归列表。

What that means is, say I start with some cost centre.这意味着,假设我从某个成本中心开始。 I get a list of all staff who are in that cost centre, and generate a list of all their subordinates.我得到了该成本中心所有员工的名单,并生成了他们所有下属的名单。 Then I get a list of all those cost centres and repeat for each of those.然后我得到所有这些成本中心的列表,并为每个成本中心重复。

I already have a number of procedures, two of which may be relevant:我已经有一些程序,其中两个可能是相关的:

CALL getCostCentre(iCostCentre) /* get a list of all staff in iCostCentre) */
CALL getSupervisees(iSupervisor) /* get a list of all staff who report to iSupervisor */

I would create a single table containing staff and supervisors, let's call it Employee, and another table for holding relationships (each table with a delete flag field and a change date field for audit trial).我将创建一个包含员工和主管的表,我们称之为员工,以及另一个用于保存关系的表(每个表都有一个删除标志字段和一个用于审计试验的更改日期字段)。 The table relationship has a subordinate and a master.表关系有从属和主控。 And a table for cost centers holding references to the employees.还有一个成本中心表,其中包含对员工的引用。 There are some open source CRMs around that you can download (use it maybe) and eventually learn how to structure your db.周围有一些开源 CRM,您可以下载(可能使用它)并最终学习如何构建您的数据库。 Regarding cost centers, you can learn from the table Group in standard CRMs关于成本中心,可以参考标准CRM中的表Group

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM