1 foreign key references 2 primary keys

Discussion in 'MySQL' started by Kuna, Jul 6, 2013.

  1. #1
    table1
    ID (PRIMARY)
     
    table2
    ID (PRIMARY)
     
    table3
    IDpar(FOREIGN KEY)
    Code (markup):
    I have 2 IDs from 2 different tables (table1 and table2) and they are primary keys. In 3. table (table3) I have IDpar which is foreign key and references ID in table1 and table2.

    if I do this:
    
    FOREIGN KEY (IDpar) REFERENCES table1(ID)
            ON UPDATE CASCADE
            ON DELETE CASCADE
    FOREIGN KEY (IDpar) REFERENCES table2(ID)
            ON UPDATE CASCADE
            ON DELETE CASCADE
    
    Code (markup):
    How will database know which value in column IDpar(table3) comes from ID(table1) or ID(table2). ID from both tables can have the same values because they are auto increment field.

    
    ID(table1)
    1
    2
     
    ID(table2)
    1
    2
     
    IDpar(table3)
    1 (ID table1)
    1 (ID table2)
    2 (ID table1)
    2 (ID table2)
    
    Code (markup):
    Now if I update ID(table1) from 1 to 3, then in table3 IDpar will be updated everywhere from 1 to 3, right?
    That should not happen because one value in IDpar comes from table1 and other from table2.
     
    Kuna, Jul 6, 2013 IP
  2. jestep

    jestep Prominent Member

    Messages:
    3,659
    Likes Received:
    215
    Best Answers:
    19
    Trophy Points:
    330
    #2
    Can you explain what you are trying to accomplish? A one-to-one foreign key can only reference a single table. If you think about it, there's no possible way the database would know what to do if a single column in table 1 was relational to a column in 2 separate tables.
     
    jestep, Jul 25, 2013 IP