簡體   English   中英

如何構建此關系數據庫

[英]How to structure this relational database

基本上,我將擁有3個具有關聯關系的表。 他們是: usersdepartmentscompany

我的問題是這樣的:

  • company可以有很多部門
  • 一個department只能隸屬於一個公司
  • user只能是一個公司的一部分
  • user可以是多個部門的一部分

這實際上就是表關系的樣子:

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

以上倍數| 行顯示一個選項,因此上面的“公司”有4個部門,依此類推。

現在我的問題是,我應該如何構建關系表?

我應該有user_departmentsuser_companycompany_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只會是Departments表的一個字段,以引用一個部門所屬的公司。 同樣,您將不需要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

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

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

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

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM