简体   繁体   中英

Referencing multiple primary key(s) in another table

I am developing a new web application and for that I also need to define its database structure.

Problem is I have a table called Department , containing:

id: int
name: varchar

And another table called Employee

id: int
name: varchar
dept: Department.id(s) (Foreign Key)

Issue is an employee could belong to multiple departments and I am unable to figure out how to store this information in the table, for eg:

If client 001 belongs to Department 004,005 and 006 than how do I store these three department keys in one column ie Employee.dept?

I figured out that one possible way could to store them as delimited strings like “004,005,006”, But for this I would have to convert them back and forth to string and int and than search the string for a particular occurrence.

Can anyone kindly help me suggesting an 'efficient' and correct solution for this problem?

Don't store those ID as comma separated value. It's a very very bad design. Properly normalize the table.

This is a Many-to-Many relationship. So you should have three tables on your schema,

Department

  • ID (PK)
  • Name

Employee

  • ID (PK)
  • Name

Employee_Department

  • DepartmentID (FK)
  • EmployeeID (FK)

so when translated to real DDL,

CREATE TABLE Department
(
    ID INT,
    NAME VARCHAR(50),
    CONSTRAINT dept_pk PRIMARY KEY (ID),
    CONSTRAINT dept_uq UNIQUE(Name)
)

CREATE TABLE Employee
(
    ID INT,
    NAME VARCHAR(50),
    CONSTRAINT Emp_pk PRIMARY KEY (ID),
    CONSTRAINT Emp_uq UNIQUE(Name)
)

CREATE TABLE Employee_Department
(
    DepartmentID INT,
    EmployeeID INT,
    CONSTRAINT empdep_pk PRIMARY KEY (DepartmentID, EmployeeID),
    CONSTRAINT empdep_FK1 FOREIGN KEY (DepartmentID)
        REFERENCES Department(ID),
    CONSTRAINT empdep_FK2 FOREIGN KEY (EmployeeID)
        REFERENCES Employee(ID)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM