Using Foreign Keys : Foreign Keys « Table « MySQL Tutorial






In MySQL, InnoDB tables support checking of foreign key constraints.

For non-InnoDB tables, REFERENCES tbl_name(col_name) clause has no actual effect.

It serves only as a comment to the column.

mysql> CREATE TABLE person (
    ->     id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
    ->     name CHAR(60) NOT NULL,
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.03 sec)

mysql>
mysql> CREATE TABLE shirt (
    ->     id SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
    ->     owner SMALLINT UNSIGNED NOT NULL REFERENCES person(id),
    ->     PRIMARY KEY (id)
    -> );
Query OK, 0 rows affected (0.03 sec)

mysql>
mysql> desc person;
+-------+----------------------+------+-----+---------+----------------+
| Field | Type                 | Null | Key | Default | Extra          |
+-------+----------------------+------+-----+---------+----------------+
| id    | smallint(5) unsigned | NO   | PRI | NULL    | auto_increment |
| name  | char(60)             | NO   |     |         |                |
+-------+----------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql> desc shirt;
+-------+----------------------+------+-----+---------+----------------+
| Field | Type                 | Null | Key | Default | Extra          |
+-------+----------------------+------+-----+---------+----------------+
| id    | smallint(5) unsigned | NO   | PRI | NULL    | auto_increment |
| owner | smallint(5) unsigned | NO   |     |         |                |
+-------+----------------------+------+-----+---------+----------------+
2 rows in set (0.00 sec)

mysql>
mysql> drop table shirt;
Query OK, 0 rows affected (0.00 sec)

mysql> drop table person;
Query OK, 0 rows affected (0.02 sec)

mysql>
mysql>








4.16.Foreign Keys
4.16.1.Using Foreign Keys
4.16.2.Using AUTO_INCREMENT
4.16.3.Implement a many-to-many map
4.16.4.One table with two foreign keys
4.16.5.Alter table to drop primary key and foreign key
4.16.6.Add Index and primary key to a table in table creation command
4.16.7.FOREIGN KEY ON DELETE CASCADE ON UPDATE CASCADE