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?
+1
A:
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).
GSerg
2009-06-04 21:02:00
+4
A:
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)
PatrikAkerstrand
2009-06-04 21:03:10
FWIW, MyISAM does parse and ignore foreign key syntax. And you don't need to declare the index redundantly since MySQL 4.1.2.
Bill Karwin
2009-06-04 22:11:42
Also make sure that both tables are InnoDB since, as Bill points out, MyISAM does not support foreign keys.
Abinadi
2009-06-05 03:28:42
I was voted down twice due to the explicit index? Harsh. I did point out that InnoDB was neccessary.
PatrikAkerstrand
2009-06-05 05:50:32