Foreign keys bring many benefits to MySQL. The following describes how to write statements for defining foreign keys in MySQL and how to handle errors when defining foreign keys in MySQL.
- mysql> CREATE TABLE categories (
- -> category_id tinyint(3) unsigned NOT NULL AUTO_INCREMENT,
- -> name varchar(30) NOT NULL,
- -> PRIMARY KEY(category_id)
- -> ) ENGINE=INNODB;
- Query OK, 0 rows affected (0.36 sec)
-
- mysql> INSERT INTO categories VALUES (1, ‘SQL Server’), (2, ‘Oracle’), (3, ‘PostgreSQL’), (4, ‘MySQL’), (5, ‘SQLite’);
- Query OK, 5 rows affected (0.48 sec)
- Records: 5 Duplicates: 0 Warnings: 0
-
- mysql> CREATE TABLE members (
- -> member_id INT(11) UNSIGNED NOT NULL,
- -> name VARCHAR(20) NOT NULL,
- -> PRIMARY KEY(member_id)
- -> ) ENGINE=INNODB;
- Query OK, 0 rows affected (0.55 sec)
-
- mysql> INSERT INTO members VALUES (1, ‘test’), (2, ‘admin’);
- Query OK, 2 rows affected (0.44 sec)
- Records: 2 Duplicates: 0 Warnings: 0
-
- mysql> CREATE TABLE articles (
- -> article_id INT(11) unsigned NOT NULL AUTO_INCREMENT,
- -> title varchar(255) NOT NULL,
- -> category_id tinyint(3) unsigned NOT NULL,
- -> member_id int(11) unsigned NOT NULL,
- -> INDEX (category_id),
- -> FOREIGN KEY (category_id) REFERENCES categories (category_id),
- -> CONSTRAINT fk_member FOREIGN KEY (member_id) REFERENCES members (member_id),
- -> PRIMARY KEY(article_id)
- -> ) ENGINE=INNODB;
- Query OK, 0 rows affected (0.63 sec)
Note: For non-InnoDB tables, the foreign key clause is ignored.