MySQL InnoDB foreign key between different databases

MysqlDatabaseForeign KeysInnodb

Mysql Problem Overview


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 ?

Mysql Solutions


Solution 1 - Mysql

I do not see any limitation on https://dev.mysql.com/doc/refman/8.0/en/create-table-foreign-keys.html.

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

Solution 2 - Mysql

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)

Solution 3 - Mysql

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;

Solution 4 - Mysql

ALTER TABLE `tablename1`
ADD CONSTRAINT `tablename1_student_id_foreign` 
FOREIGN KEY (`tablename1`.`id`) 
REFERENCES `db2`.`tablename2`(`id`)
ON DELETE CASCADE ON UPDATE CASCADE;

if we have table calling answers in db1 and student in db2 calling ramiyusu_offline

we must type as below

ALTER TABLE `answers`
ADD CONSTRAINT `answers_student_id_foreign` 
FOREIGN KEY (`id`)
REFERENCES `ramiyusu_offline`.`student`(`id`) 
ON DELETE CASCADE ON UPDATE CASCADE;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlaaView Question on Stackoverflow
Solution 1 - MysqlBarsMonsterView Answer on Stackoverflow
Solution 2 - MysqlSpilarixView Answer on Stackoverflow
Solution 3 - MysqlSalimView Answer on Stackoverflow
Solution 4 - MysqlHosam ElzaghView Answer on Stackoverflow