How to Add a Foreign Key to MySQL
MySQL is a free database server used to create dynamic web pages. Foreign keys link to a primary key in your tables. These keys are columns in your MySQL tables. They link related records in separate tables (e.g., a customer linked to an order in a separate "orders" table). You create foreign keys using the MySQL console included with the database engine.
Instructions
-
-
1
Click the Windows "Start" button and click "All Programs." Click "MySQL" and then click "MySQL Workbench" to open your main console.
-
2
Click "Edit SQL Script" in the main console window. This opens a SQL editor where you create the foreign key.
-
-
3
Type the following code into your editor:
alter table table_name add constraint key_name foreign key
references tbl_name primary_key
The first line sets the foreign key. Replace "table_name" with the name of your table. "Key_name" is the name of the column in your table you want to set as the foreign key. The second line is the primary key information to link to the foreign key. Replace "tbl_name" with the table that contains the primary key and "primary_key" with the primary key column name.
-
4
Click "Run" to run your SQL statement. The foreign key is created, and your tables are set up with the linked attributes.
-
1
References
- Photo Credit Comstock/Comstock/Getty Images