Home » Mysql » MySQL InnoDB foreign key between different databases

MySQL InnoDB foreign key between different databases

Posted by: admin November 1, 2017 Leave a comment

Questions:

I would like to know if it’s possible in InnoDB in MySQL to have a table with foreign key that references another table in a different database ?

And if so, how this can be done ?

Answers:

I do not see any limitation on http://dev.mysql.com/doc/refman/5.1/en/innodb-foreign-key-constraints.html .

So just use otherdb.othertable and you will be good.

Questions:
Answers:

It’s possible : Link to do it

Example (Table1 is in database1 and HelloTable is in database2) :

ALTER TABLE Table1 
ADD foreign key FK_table1(ColumnNameFromTable1)
REFERENCES db2.HelloTable(ColumnNameFromHelloTable)

Questions:
Answers:

Below is how to add a foreign key on table t2, reference from table db1.historial(codh):

alter table t2
add foreign key FK_t2(micod2)
    references db1.historial(codh)
    on delete cascade
    on update cascade;