MySQL InnoDB Foreign Key Referencing Another Database
In MySQL InnoDB, it is possible to establish foreign key relationships between tables in different databases. This feature allows you to enforce referential integrity across database boundaries, ensuring data consistency.
Method:
To create a foreign key that references a table in a different database, simply specify the database name followed by the table name in the FOREIGN KEY clause. The syntax is as follows:
ALTER TABLE your_table ADD FOREIGN KEY (your_column) REFERENCES otherdb.othertable(other_column);
For example, consider two databases: db1 and db2. Suppose we have a table users in db1 and a table orders in db2. We can establish a foreign key in the orders table to reference the users table as follows:
ALTER TABLE orders ADD FOREIGN KEY (user_id) REFERENCES db1.users(id);
This foreign key will ensure that every user_id in the orders table has a corresponding id in the users table in db1.
Note:
The databases involved in the foreign key relationship must be on the same server. Cross-server foreign keys are not supported in MySQL InnoDB.
以上がMySQL InnoDB 外部キーは異なるデータベースにまたがることはできますか?の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。