开发者

Database design: How to restrict a n:m relation by other relations?

I think it's best to ask based on an example: There are people, customers and projects.

People to customers is a n:m relationship. People can work for multiple customers.

Projects to customers is a 1:n relationship. One project always belongs to a certain customers, but a customer of course can have multiple active projects.

People to customers is a n:m relationship, but restricted by project to customer and people to customer assignments.

More details: Some of our people work for multiple customers, but only for a few projects of those customers.

Say customer A has projects 1,2,3 and cu开发者_运维知识库stomer B has projects 4,5,6.

Now Fred works for customer A on project 1 and for customer B on projects 5 and 6. Tim, instead, works for customer A on project 2,3 and for customer B on project 6. Our special guy Nick works only for customer B, but is currently NOT assigned to any project. The customer can assign him to a project later on.

Now, how can I ensure, using a good relational database design, that I can assign people to customers (like Nick) without a project, AND, later on, can assign them to projects of any customer - restricted to those that they are assigned to.

So do I need to design my tables so that the database model ensures that it is not possible to assign Nick to project 1,2 or 3 without first assigning him to customer A?

Thanks for any ideas :)


Here's an example in SQL:

CREATE TABLE Project
 (ProjectID INT NOT NULL PRIMARY KEY, CustomerID INT NOT NULL,
 UNIQUE (ProjectID, CustomerID));

CREATE TABLE EmployeeProject
 (EmployeeID INT NOT NULL, ProjectID INT NOT NULL, CustomerID INT NOT NULL,
  FOREIGN KEY (EmployeeID, CustomerID) REFERENCES EmployeeCustomer (EmployeeID, CustomerID),
  FOREIGN KEY (ProjectID, CustomerID) REFERENCES Project (ProjectID, CustomerID),
  PRIMARY KEY (EmployeeID, ProjectID));


In this model the Project is a sub-type of the Assignment. For example, assignment can be of type P = project or O = Open.

  • Each assignment (open or project) belongs to one customer only.
  • There can be several employees working on one assignment at different time-periods.

The re-assigning constraint should be handled in the business logic (application layer). Switching from an open assignment to a project can be done by closing the period for that employee assignment (EndDate) and defining a new assignment of type = project for that employee-customer combination.

Database design: How to restrict a n:m relation by other relations?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜