时间:2022-12-06 01:50
在mysql修改表为外键的示例:
country 表是父表,country_id是主键,city是子表,外键为country_id,和country表的主键country_id对应,在创建表的时候添加外键,示例:
createtablecountry(country_idsmallintunsignednotnullauto_increment,
countryvarchar(50)notnull,
last_updatetimestampnotnulldefaultcurrent_timestamponupdatecurrent_timestamp,
primarykey(country_id)
)engine=INNODBdefaultcharset=utf8;
CREATETABLE`city`(
`city_id`smallint(5)unsignedNOTNULLauto_increment,
`city`varchar(50)NOTNULL,
`country_id`smallint(5)unsignedNOTNULL,
`last_update`timestampNOTNULLdefaultCURRENT_TIMESTAMPonupdateCURRENT_TIMESTAMP,
PRIMARYKEY(`city_id`),
KEY`idx_fk_country_id`(`country_id`),
CONSTRAINT`fk_city_country`FOREIGNKEY(`country_id`)REFERENCES`country`(`country_id`)ondeleterestrictONUPDATECASCADE
)ENGINE=InnoDBDEFAULTCHARSET=utf8;
在建表后添加外键的示例:
ALTERTABLEcityADDFOREIGNKEY(country_id)REFERENCES`country`(country_id);