在mysql怎么修改表为外键

625
2021/3/18 12:52:41
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在mysql怎么修改表为外键

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);


辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: 连接mysql数据库报错1045怎么解决