Let us understand how foreign keys can be used in MySQL −
InnoDB tables support checking foreign key constraints. A foreign key constraint isn’t required just to join two tables. It can be used while defining a column that needs to be used, for storage engines apart from InnoDB. The REFERENCES tableName(colName) has no real effect and serves as a comment to the user that the column currently being defined is intended to refer to column in a different table.
MySQL doesn’t do any check to ensure that ‘colName’ actually exists in the ‘tableName’ or whethr ‘tableName’ itself truly exists.
In the parent table, the foreign key will act as a primary key. Let us see an example create a table.
mysql> create table StudentEnrollment −> ( −> StudentId int, −> StudentName varchar(200), −> StudentFKPK int −> ); Query OK, 0 rows affected (0.91 sec)
mysql> create table College −> ( −> StudentFKPK int, −> CourseId int, −> CourseName varchar(200), −> CollegeName varchar(200), −> primary key(StudentFKPK) −> ); Query OK, 0 rows affected (0.46 sec)
In the parent table, the column ‘StudentFKPK’ is a primary key. We will use the ALTER command to add a foreign key.
The following is the syntax to add a foreign key.
ALTER table yourChildTableName add constraint anyConstraintName foreign key(primary key column name for parent table) references College(primary key column name for parent table);