Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding foreign key on multiple columns

I'm trying to create a foreign key on two columns of a table to point to the same column of another table, but I seem to get an error...

Here's what I do:

CREATE TABLE test2 (
  ID INT NOT NULL AUTO_INCREMENT,  
  col1 INT NOT NULL,
  col2 INT NOT NULL, 
  PRIMARY KEY (ID),
  CONSTRAINT fk FOREIGN KEY (col1, col2)
                REFERENCES test1(ID, ID)
  ON UPDATE CASCADE
  ON DELETE RESTRICT
) ENGINE=InnoDB;

But I get

ERROR 1005 (HY000): Can't create table 'DB.test2' (errno: 150)

If I only have one column, however, the table is correctly created.

Could someone point out to me where the error is?

Thanks n

like image 465
nico Avatar asked Feb 16 '11 23:02

nico


People also ask

Can we create foreign key on multiple columns?

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 parent table?

No. A foreign key constraint names exactly which table and column(s) it references, and it must reference the same table and column(s) on every row.

Does the foreign key go on the many side?

Whichever one is not the primary key is the foreign key. In one-to-many relationships, the FK goes on the "many" side. It can't go on the "one" side because that's where the PK goes and the definition of a primary key includes disallowing duplicates.

How many columns can you have as a foreign key in the table?

A table can reference a maximum of 253 other tables and columns as foreign keys (outgoing references).


1 Answers

Tried it here and got the same error. This works though:

CREATE TABLE test2 (
  ID INT NOT NULL AUTO_INCREMENT,  
  col1 INT NOT NULL,
  col2 INT NOT NULL, 
  PRIMARY KEY (ID),
  CONSTRAINT fk FOREIGN KEY (col1)
                REFERENCES test1(ID)
  ON UPDATE CASCADE
  ON DELETE RESTRICT,
  CONSTRAINT fk2 FOREIGN KEY (col2)
                REFERENCES test1(ID)
  ON UPDATE CASCADE
  ON DELETE RESTRICT

) ENGINE=InnoDB

Yes, I know - your script should work (even if it doesn't seem to make much sense). Yet, I guess this new version is better.

like image 108
rsenna Avatar answered Sep 24 '22 01:09

rsenna