MySQL中如何定义外键(2)
来源:asp之家 时间:2010-03-09 16:18:00
级联操作
考虑以下这种情况:
技术人员发现,一个月之前输入到parts表中的某个系列的cpu(可能有很多款)的型号全都输错了一个字母,现在需要改正。我们希望的是,当parts表中那些 Referenced Column 有所变化时,相应表中的 Referencing Column 也能自动更正。
可以在定义外键的时候,在最后加入这样的关键字:
ON UPDATE CASCADE;
即在主表更新时,子表(们)产生连锁更新动作,似乎有些人喜欢把这个叫“级联”操作。
如果把这语句完整的写出来,就是:
ALTER TABLE pc ADD CONSTRAINT fk_cpu_model
FOREIGN KEY (cpumodel)
REFERENCES parts(model)
ON UPDATE CASCADE;
除了CASCADE外,还有RESTRICT(禁止主表变更)、SET NULL
关于对该文补充:
如果需要在主表删除记录时,当子表有对应记录则不允许删除,就加上 ON delete restrict 。完整案例如下:
两个表,国家和城市,城市中的country_id是外键。
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. 总结
——-
引入外键的缺点是会使速度和性能下降,当然外键所带来的优点还有很多。