在mysql修改表為外鍵的示例:
country 表是父表,country_id是主鍵,city是子表,外鍵為country_id,和country表的主鍵country_id對應,在創建表的時候添加外鍵,示例:
create table country(country_id smallint unsigned not null auto_increment,
country varchar(50) not null,
last_update timestamp not null default current_timestamp on update current_timestamp,
primary key(country_id)
)engine=INNODB default charset=utf8;
CREATE TABLE `city` (
`city_id` smallint(5) unsigned NOT NULL auto_increment,
`city` varchar(50) NOT NULL,
`country_id` smallint(5) unsigned NOT NULL,
`last_update` timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_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;
在建表后添加外鍵的示例:
ALTER TABLE city ADD FOREIGN KEY (country_id) REFERENCES `country`(country_id);