I have a table that has a primary key consisting of two columns (product_id, attribute_id). I have another table that needs to reference this table. How can I make a foreign key in the other table to link it to a row in the table with two primary keys?
MySQL allows us to add a FOREIGN KEY constraint on multiple columns in a table. The condition is that each Foreign Key in the child table must refer to the different parent table.
The FOREIGN KEY constraint differs from the PRIMARY KEY constraint in that, you can create only one PRIMARY KEY per each table, with the ability to create multiple FOREIGN KEY constraints in each table by referencing multiple parent table.
That's impossible. A FOREIGN KEY constraint can only point to one table and each table can only have one PRIMARY KEY constraint. Or you can have multiple FOREIGN KEY constraints on the same column(s) referencing one PRIMARY KEY of a (different) table each.
Something like this ought to do it:
CREATE TABLE MyReferencingTable AS ( [COLUMN DEFINITIONS] refcol1 INT NOT NULL, rofcol2 INT NOT NULL, CONSTRAINT fk_mrt_ot FOREIGN KEY (refcol1, refcol2) REFERENCES OtherTable(col1, col2) ) ENGINE=InnoDB;
There can only be one primary key on a table. The fact in can consist of more than one field does not increase number of primary keys, there's still one.
Since a part of the PK pair is not unique, you obviously have to create a foreign key that refers to two fields as well: REFERENCES t1 (f1, f2).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With