简体   繁体   English

MySQL外键约束

[英]MySQL Foreign Key Constraint

I'm having some issues with a foreign key constraint, and am probably not putting the code together properly. 我遇到了一些外键约束的问题,而且可能没有正确地将代码放在一起。

The idea is that the airports table will only accept a type value that is in the apType table. 这个想法是,机场表只接受apType表中的类型值。 If the type is not in the apType table, it should generate an error. 如果类型不在apType表中,则应该生成错误。 However, I have been testing this and I am unable to get it to generate an error, it just places the type entered into the database and is happy with it. 但是,我一直在测试这个并且我无法让它生成错误,它只是将输入的类型放入数据库并且对此感到满意。

Airport Table: 机场表:

 CREATE TABLE `airport`(
`id` int primary key AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`rwyCount` int,
`lat` float(6),
`lon` float(6),
`type` varchar(255), 
constraint FOREIGN KEY (type) REFERENCES apType(type) match simple
)ENGINE=MyISAM DEFAULT CHARSET=latin1;

apType Table: apType表:

CREATE TABLE `apType`(
`id` int primary key AUTO_INCREMENT,
`type` varchar(255) NOT NULL
 )ENGINE=MyISAM DEFAULT CHARSET=latin1;

insert of values for apType (these are the only values that should be valid): 插入apType的值(这些是唯一应该有效的值):

INSERT INTO `apType` (`type`) VALUES ('private'),('public'),('military');

Insert that should generate an error: 插入应该生成错误:

 insert into `airport` (`name` , `rwyCount` , `type` , `lat` , `lon`) values ('failland', 3 , 'space', 45.588611, -122.5975);

Can anyone figure out this issue? 有人能解决这个问题吗?

It appears that foreign keys have not yet been implemented in the DB engine that you are using. 看来,您正在使用的数据库引擎中尚未实现外键。 Why doesn't MySQL's MyISAM engine support Foreign keys? 为什么MySQL的MyISAM引擎不支持外键?

Maybe consider switching to InnoDb? 也许考虑转换到InnoDb?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM