2022
我们一起努力

在mysql怎么修改表为外键

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

赞(0)
文章名称:《在mysql怎么修改表为外键》
文章链接:https://www.fzvps.com/65518.html
本站文章来源于互联网,如有侵权,请联系管理删除,本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。
图片版权归属各自创作者所有,图片水印出于防止被无耻之徒盗取劳动成果的目的。

评论 抢沙发

评论前必须登录!