mysql - 如何构建这个关系数据库

标签 mysql sql schema erd

基本上我会有 3 个有关系的表。它们是:用户部门公司

我遇到的问题是:

  • 一个公司可以有多个部门
  • 一个部门只能隶属于一个公司
  • 一个用户只能是一个公司的一员
  • 用户可以属于许多部门

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

                    ____________________
                    | | | |            |
                    | | | |            |
--------      --------------      -----------
| 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 只是部门表的一个字段,用于引用部门所属的公司。同样,您不需要 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/

相关文章:

c# 将 linq 数据库记录转换为类实例

mysql - 我们什么时候应该使用一对一关系模型而不是将属性添加到同一个表?

MySQL有时会减少字段值

c++ - 如何在C++中使用MySQL的STR_TO_DATE?

mysql - 塞舌尔和叙利亚的 ip2nation 数据库记录是否奇怪?

sql - 当我尝试使用 sp_executesql 时,为什么会得到 "Procedure expects parameter ' @statement' of type 'ntext/nchar/nvarchar' ."?

mysql - 用于存储调查问卷和多项选择答案的数据库架构

mysql - 1 点击Mysql schema to diagram convert?

php - 从mysql数据库拉取数据之前确保wamp服务器在线 -Android

php - 使用端口 3307 连接到 MySql