基本上我会有 3 个有关系的表。它们是:用户
、部门
和公司
。
我遇到的问题是:
- 一个
公司
可以有多个部门 - 一个
部门
只能隶属于一个公司 - 一个
用户
只能是一个公司的一员 用户
可以属于许多部门
这基本上就是表关系的样子:
____________________
| | | | |
| | | | |
-------- -------------- -----------
| user | | department | | company |
-------- -------------- -----------
| | | | | | | |
| | | | | | | |
| ___________________ |
| |
| |
| |
_______________________________________
上面的多行|
显示了一个选项,所以上面的“公司”有4个部门等等。
现在我的问题是,我应该如何构建关系表?
我应该有 user_departments
、user_company
和 company_departments
表吗?
基本上看起来像这样:
--------------------
| user_departments |
--------------------------------
| id | user_id | department_id |
--------------------------------
----------------
| user_company |
-----------------------------
| id | user_id | company_id |
-----------------------------
-----------------------
| company_departments |
-----------------------------------
| id | company_id | department_id |
-----------------------------------
或者是否有任何其他替代方案可供我考虑/实现,而不是我要走的道路,因为它似乎只会变得越来越复杂?
最佳答案
您实际上是在建立冗余关系。您应该不需要 company_departments,company_id 只是部门表的一个字段,用于引用部门所属的公司。同样,您不需要 user_company 表,但需要 user_departments 表;这是由于用户-部门关系实际上是多对多的。
对于您给出的示例,您应该只需要四个表。
company: company_id, other company info (such as name)
department: department_id, company_id (referencing the company record), other department info
user: user_id, company_id (referencing the company record), other user info
user_departments: user_id, department_id, perhaps information such as user's role in department, or if you want historical data preserved dates assigned to and removed from department
关于mysql - 如何构建这个关系数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30065494/