温馨提示×

在mysql怎么修改表为外键

小新
373
2021-03-18 12:52:41
栏目: 云计算
亿速云mysql数据库,读写分离,安全稳定,弹性扩容,低至0.3元/天!! 点击查看>>

在mysql怎么修改表为外键

mysql修改表为外键的示例:

country 表是父表,country_id是主键,city是子表,外键为country_id,和country表的主键country_id对应,在创建表的时候添加外键,示例:

create table country(

country_id smallint unsigned not null auto_increment,

country varchar(50not 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(5unsigned NOT NULL auto_increment,

`city` varchar(50NOT NULL,

`country_id` smallint(5unsigned 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);

亿速云「云数据库 MySQL」免部署即开即用,比自行安装部署数据库高出1倍以上的性能,双节点冗余防止单节点故障,数据自动定期备份随时恢复。点击查看>>

推荐阅读:SQL怎么为表中添加外键

0