MySQL Foreign Keys: How to Add Them
There are several methods to add foreign keys in MySQL.
- When creating a table, you can add a foreign key constraint using the FOREIGN KEY keyword. For example:
- Create a table with columns and specify a foreign key referencing another table.
- To add a foreign key constraint to an existing table: You can use the ALTER TABLE statement to add a foreign key constraint to an existing table. For example:
- Modify the table by adding a foreign key constraint named 外键约束名 on the column 外键列名, referencing the 关联表名 table on the 关联列名 column.
- The CREATE INDEX statement can be used to create a foreign key index, which can then be used for foreign key associations. For example: “`sqlCREATE INDEX index_name ON table_name (foreign_key_column);“`
Add a foreign key constraint to a table with the syntax:
ALTER TABLE table_name ADD CONSTRAINT constraint_name FOREIGN KEY (column_name) REFERENCES related_table_name (related_column_name);
Regardless of the method used, when adding foreign keys, it is important to make sure that the data type and length of the associated columns match those of the linked columns, or else an error will occur.