Home >Database >Mysql Tutorial >Can MySQL InnoDB Create Foreign Keys Between Tables in Different Databases?

Can MySQL InnoDB Create Foreign Keys Between Tables in Different Databases?

Patricia Arquette
Patricia ArquetteOriginal
2024-11-19 00:13:02436browse

Can MySQL InnoDB Create Foreign Keys Between Tables in Different Databases?

MySQL InnoDB Foreign Key Constraints Across Databases

Can InnoDB within MySQL maintain a foreign key relationship between tables in separate databases?

Answer:

Yes, MySQL allows foreign key constraints to reference tables in different databases.

Implementation:

To establish a cross-database foreign key constraint:

  1. Use the otherdb.othertable syntax to specify the referenced table in the foreign key definition.
  2. Ensure that both databases are registered and accessible by the MySQL instance using the GRANT command.

For example, to create a foreign key constraint in the mytable table in the mydb database that references the othertable table in the otherdb database, use the following syntax:

ALTER TABLE mydb.mytable
ADD FOREIGN KEY (col1) REFERENCES otherdb.othertable (col2);

The above is the detailed content of Can MySQL InnoDB Create Foreign Keys Between Tables in Different Databases?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn