Two foreign keys referencing the same primary key

后端 未结 4 2145
心在旅途
心在旅途 2020-12-08 09:55

Is this okay to have two foreign keys in one table referencing one primary key of other table?

EmployeeID is a primary key in the employee table and appearing as a f

相关标签:
4条回答
  • 2020-12-08 10:32

    I would go with option 1. It is perfectly fine to have two foreign key columns referencing the same primary key column in a different table since each foreign key value will reference a different record in the related table.

    I'm sure option 2 would work, but you would essentially have a 1-to-1 relationship between TIMESHEET_TABLE and TIMESHEET_FILLED_BY, making two tables unnecessary and more difficult to maintain.

    In fact, if both ENTERED_BY and TIMESHEET_FOR are required in pairs, using option 1 makes far more sense because this is automatically enforced by the database and foreign keys.

    0 讨论(0)
  • 2020-12-08 10:43

    yes, there is no problem with that...you can use a primary key of one table in other table as foreign key two times.

    0 讨论(0)
  • 2020-12-08 10:51

    Option 1 is a perfect solution. You may define foreign key constraint as following

    1st foreign key constraint for Timesheet_For column

    ALTER TABLE TIMESHEETTABLE 
    ADD CONSTRAINT fk_TimesheetTable_EmployeeTable
    FOREIGN KEY (TIMESHEET_FOR)
    REFERENCES EMPLOYEETABLE(EMPLOYEE_ID)
    

    2nd foreign key constraint for Entered_By column

    ALTER TABLE TIMESHEETTABLE 
    ADD CONSTRAINT fk_TimesheetTable_EmployeeTable_1
    FOREIGN KEY (ENTERED_BY)
    REFERENCES EMPLOYEETABLE(EMPLOYEE_ID)
    
    0 讨论(0)
  • 2020-12-08 10:51

    Your query like :

    SELECT t.EMPLOYEE_ID, a.NAME as TimeSheetFor, b.NAME as EnteredBy 
    FROM timesheet t
    JOIN employee a ON t.timesheet_for =a.employee_id
    JOIN employee b ON t.entered_by = b.employee_id
    

    Using this query you will get result as you want.

    0 讨论(0)
提交回复
热议问题