How to add a foreign key when creating a table in MySQL?
When adding a foreign key in MySQL, the FOREIGN KEY keyword is used to specify the foreign key constraint. The following is an example SQL statement to create a table and add a foreign key:
CREATE TABLE table1 (
id INT PRIMARY KEY,
name VARCHAR(50)
);
CREATE TABLE table2 (
id INT PRIMARY KEY,
table1_id INT,
FOREIGN KEY (table1_id) REFERENCES table1(id)
);
In the example above, we first created two tables, table1 and table2. We then added a foreign key constraint in table2 that links the table1_id column in table2 to the id column in table1. This allows us to use the id from table1 as a foreign key in table2.