MySQL中如何定义外键
假如某个电脑生产商,它的数据库中保存着整机和配件的产品信息。用来保存整机产品信息的表叫做pc;用来保存配件供货信息的表叫做parts。
在pc表中有一个字段,用来描述这款电脑所使用的CPU型号;在parts表中相应有一个字段,描述的正是CPU的型号,我们可以把它想成是全部CPU的型号列表。
很显然,这个厂家生产的电脑,其使用的CPU一定是供货信息表(parts)中存在的型号。这时,两个表中就存在一种约束关系(constraint)——pc表中的CPU型号受到parts表中型号的约束。
首先我们来创建parts表:
Create table country(country_id smallint unsigned not null auto_increment,country varchar(50) not null,last_update timestamp not null,primary key(country_id))engine=innoDB default charset=utf8;Create table city(city_id smallint unsigned not null auto_increment,city varchar(50) not null,country_id smallint unsigned not null,last_update timestamp not null default current_timestamp on update curren_timestamp,Primary key(city_id),key idx_fk_country_id (country_id),constraint fk_city_country Foreign Key(country_id) References country(country_id) on DELETE restrict ON update cascade)engine=innoDB default charset=utf8;
删除外键:
删除外键定义
—————
定义外键的时候articles.member_id外键比articles.category_id子句多了一个CONSTRAINT fk_member ?
这个fk_member就是用来删除外键定义用的,如下所示:
mysql> ALTER TABLE articles DROP FOREIGN KEY fk_member;
Query OK, 1 row affected (0.25 sec)
Records: 1 Duplicates: 0 Warnings: 0
这样articles.member_id外键定义就被删除了,但是如果定义时没有指定CONSTRAINT fk_symbol (即外键符号)时该怎么删除呢?别急,没有指定时,MySQL会自己创建一个,可以通过以下命令查看:
mysql> SHOW CREATE TABLE articles;
+———-+————————————+
| Table | Create Table |
+———-+————————————+
| articles | CREATE TABLE `articles` (
`article_id` int(11) unsigned NOT NULL auto_increment,
`category_id` tinyint(3) unsigned NOT NULL,
`member_id` int(11) unsigned NOT NULL,
`title` varchar(255) NOT NULL,
PRIMARY KEY (`article_id`),
KEY `category_id` (`category_id`),
KEY `member_id` (`member_id`),
CONSTRAINT `articles_ibfk_1` FOREIGN KEY (`category_id`) REFERENCES `categories` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 |
+———-+————————————+
1 row in set (0.01 sec)
可以看出articles.category_id的外键符号为articles_ibfk_1,因为就可以执行以下命令删除外键定义:
mysql> ALTER TABLE articles DROP FOREIGN KEY articles_ibfk_1;
Query OK, 1 row affected (0.66 sec)
Records: 1 Duplicates: 0 Warnings: 0
6. 总结
——-
引入外键的缺点是会使速度和性能下降,当然外键所带来的优点还有很多。