Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple-column foreign key in MySQL?

Tags:

mysql

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?

like image 218
James Skidmore Avatar asked Jun 04 '09 20:06

James Skidmore


People also ask

Can multiple columns be a foreign key?

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.

Can a foreign key reference multiple columns of the 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.

Can a foreign key be multiple attributes?

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.


2 Answers

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; 
  • MySQL requires foreign keys to be indexed, hence the index on the referencing columns
  • Use of the constraint syntax enables you to name a constraint, making it easier to alter and drop at a later time if needed.
  • InnoDB enforces foreign keys, MyISAM does not. (The syntax is parsed but ignored)
like image 178
PatrikAkerstrand Avatar answered Sep 22 '22 16:09

PatrikAkerstrand


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).

like image 39
GSerg Avatar answered Sep 23 '22 16:09

GSerg