MySQL定义外键的方法是每个学习MySQL的人都需要掌握的知识,下文就对MySQL定义外键的语句写法进行了详细的阐述,供您参考。
外键为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子句会被忽略掉。
时间: 2024-09-29 16:43:31