Using Foreign Keys : Foreign Keys : Table MySQL TUTORIALS


MySQL TUTORIALS » Table » Foreign Keys »

 

Using Foreign Keys


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(60NOT NULL,
    ->     PRIMARY KEY (id)
    -> );
Query OK, 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, rows affected (0.03 sec)

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

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

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

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

mysql>
mysql>



Leave a Comment / Note


 
Verification is used to prevent unwanted posts (spam). .

Follow Navioo On Twitter

MySQL TUTORIALS

 Navioo Table
» Foreign Keys