如何构建这个关系数据库

How to structure this relational database

基本上我会有 3 个 table 有关系。它们是:usersdepartmentscompany

我遇到的问题是:

这基本上就是 table 关系的样子:

                    ____________________
                    | | | |            |
                    | | | |            |
--------      --------------      -----------
| user |      | department |      | company |
--------      --------------      -----------
 |   |         | | | | |               |
 |   |         | | | | |               |
 |   ___________________               |
 |                                     |
 |                                     |
 |                                     |
 _______________________________________

上面的多个|行显示一个选项,所以上面的"company"有4个部门等等

现在我的问题是,我应该如何构建关系 tables?

我应该有 user_departmentsuser_companycompany_departments table 吗?

基本上看起来像这样:

--------------------
| user_departments |
--------------------------------
| id | user_id | department_id |
--------------------------------

----------------
| user_company |
-----------------------------
| id | user_id | company_id |
-----------------------------

-----------------------
| company_departments |
-----------------------------------
| id | company_id | department_id |
-----------------------------------

或者我是否有其他选择 consider/implement 而不是我要走的路,因为它似乎只会变得越来越复杂?

你实际上是在建立多余的关系。您应该不需要 company_departments,company_id 只是部门 table 的一个字段来引用部门所属的公司。同样,您不需要 user_company table,但需要 user_departments;这是由于用户-部门关系实际上是多对多的。

根据您给出的示例,您应该只需要四个 tables。

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

这是您使用的格式的布局:

---------
| users |
--------------------------------
| id | name | company_id | ... |
--------------------------------

-----------
| company |
-------------------
| id | name | ... |
-------------------

-----------
| departments |
--------------------------------
| id | name | company_id | ... |
--------------------------------

--------------------
| user_departments |
--------------------------------
| id | user_id | department_id |
--------------------------------