📜  mysql alter add foreign key - SQL (1)

📅  最后修改于: 2023-12-03 15:03:04.517000             🧑  作者: Mango

MYSQL ALTER ADD FOREIGN KEY - SQL

When working with MySQL databases, it is very common to have multiple tables with some sort of relationship between them. These relationships can be defined using foreign keys, which ensure referential integrity between the tables.

In this markdown, we will focus on how to add a foreign key to an existing table using the MySQL ALTER ADD FOREIGN KEY SQL statement.

Syntax

The syntax for adding a foreign key to an existing table is as follows:

ALTER TABLE table_name
ADD CONSTRAINT foreign_key_name
FOREIGN KEY (column_name) REFERENCES table_to_referenced(column_name_to_reference);
  • table_name: The name of the table to which the foreign key is to be added.
  • foreign_key_name: The name of the foreign key that is being added.
  • column_name: The name of the column in the table for which the foreign key is being added.
  • table_to_referenced: The name of the table that the foreign key references.
  • column_name_to_reference: The name of the column in the referenced table that the foreign key points to.
Example

Let's say we have two tables called orders and customers, where the orders table has a foreign key relationship with the customers table. We can create this relationship using the following SQL statement:

ALTER TABLE orders
ADD CONSTRAINT fk_customer_order
FOREIGN KEY (customer_id) REFERENCES customers(id);

This statement adds a foreign key constraint to the orders table, where the customer_id column references the id column of the customers table. The fk_customer_order is the name we give to our foreign key constraint.

Note that in order for this statement to work, the customer_id column in the orders table must be of the same data type as the id column in the customers table.

Conclusion

Adding a foreign key to an existing table in MySQL is a simple process that can be accomplished using the ALTER ADD FOREIGN KEY SQL statement. By enforcing referential integrity, foreign keys help maintain the integrity of our database and ensure that our data is consistent.