The foreign key can be used to create a relationship between tables. The foreign key relationship can be one to one or one to many. A foreign key matches another field of another table.
One to One relationship − One record from one table will be linked to one record in another table.
One to Many relationships − One record will be linked to multiple records in another table.
The following is an example. First, we will create a table. The CREATE command is used to create a table.
mysql> create table tblF - > ( - > id int , - > FirstName varchar(100), - > FK_PK int - > ); Query OK, 0 rows affected (0.57 sec)
To create a second table.
mysql> create table tblP - > ( - > FK_PK int, - > LastName varchar(100), - > primary key(FK_PK) - > ); Query OK, 0 rows affected (0.94 sec)
The following is the syntax to create a foreign key.
mysql> ALTER table tblF add constraint ConstFK foreign key(FK_PK) references tblP(FK_PK); Query OK, 0 rows affected (2.17 sec) Records: 0 Duplicates: 0 Warnings: 0
Check if foreign key has been created with the help of DESC command.
mysql> DESC tblF;
The following is the output.
+-----------+--------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +-----------+--------------+------+-----+---------+-------+ | id | int(11) | YES | | NULL | | | FirstName | varchar(100) | YES | | NULL | | | FK_PK | int(11) | YES | MUL | NULL | | +-----------+--------------+------+-----+---------+-------+ 3 rows in set (0.05 sec)