5

I am not sure what will be the best way to enforce participation in the following database design (can be for SQL server, Oracle, mySQL etc.). I have two tables: Factory and Worker. I have created two rules for the design: 1) Each factory hires at least one (or many) workers. 2) Each worker works for exactly one and only one factory.

I have created an ERD for the design:

[Factory]-||--- hire ---|<-[Worker]

The FACTORY table looks like this:

Factory_ID (PK) Factory_Name

1 A
2 B
3 C

The WORKER table looks like this:

Worker_ID (PK) Worker_Name Factory_ID (FK)

1 Tom 2
2 Ann 1
3 Jan 1

In the worker table, the Factory_ID is the foreign key (FK) and it is set to NOT NULL because (the ERD said) each worker have to work for one factory and only one. This participation can be enforced by setting the FK (the Factory_ID field in the Worker table) to not null.

Here is my question, what is the best way to enforce the participation of - Each factory hires at least one workers? I.e. I need to make sure each factory_id have to be referenced in the worker table at least once. So now factory #3 does not hire anyone which violates the participation rule in the ERD.

I am wondering what will be the best way to enforce this participation?

4

1 回答 1

5

1+ 关系约束通常在应用层实现。

  • 存储过程
  • 触发器
  • 后端业务层
  • 前端
  • 前面的任意组合

问题是有一个时间概念可以预见:在这种限制下,您的工厂需要一个工人,但您的工人自己需要一个工厂:这根本不可能以同步方式实施此规则。

一种解决方案可能是管理一种后台以单独添加元素(出于管理目的),然后在公共前端实施适当的限制以匹配您的 1+ 要求。例如:

  1. 将员工移至公司时,检查是否至少还剩一个
  2. 当员工更换公司时实施公司更换,以确保每位员工始终只有一家公司。
于 2013-04-07T21:30:38.747 回答