外鍵為MySQL帶來了諸多的好處,下面就為您介紹MySQL定義外鍵的語句寫法,以及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)
注意:對於非InnoDB表,FOREIGN KEY子句會被忽略掉。