我有两个表,table1是一个列ID的父表,table2是一个列IDFromTable1(不是实际的名称),当我把一个FK IDFromTable1到ID在table1,我得到的错误外键约束是不正确形成的错误。我想删除表2记录,如果表1记录被删除。谢谢你的帮助

ALTER TABLE `table2`  
   ADD CONSTRAINT `FK1` 
      FOREIGN KEY (`IDFromTable1`) REFERENCES `table1` (`ID`) 
      ON UPDATE CASCADE 
      ON DELETE CASCADE;

如果还需要其他信息,请告诉我。我是mysql的新手


当前回答

检查表格引擎,两个表格必须是相同的引擎,这对我帮助很大。

其他回答

我在使用Alter table在两个表之间添加外键时遇到了问题,帮助我的是确保我试图添加外键关系的每一列都被索引。在PHP myAdmin中这样做: 转到表并单击结构选项卡。 点击索引选项可以索引所需的列,如下图所示:

一旦我索引了我试图用外键引用的两列,我就能够成功地使用alter表并创建外键关系。你会看到列的索引如下面的截图:

注意zip_code是如何在两个表中显示的。

试着运行以下命令:

show create table Parent

//and check if type for both tables are the same, like myISAM or innoDB, etc
//Other aspects to check with this error message: the columns used as foreign 
keys must be indexed, they must be of the same type 
(if i.e one is of type smallint(5) and the other of type smallint(6), 
it won't work), and, if they are integers, they should be unsigned.

//or check for charsets
show variables like "character_set_database";
show variables like "collation_database";

//edited: try something like this
ALTER TABLE table2
ADD CONSTRAINT fk_IdTable2
FOREIGN KEY (Table1_Id)
REFERENCES Table1(Table1_Id)
ON UPDATE CASCADE 
ON DELETE CASCADE;

我为这个损失了好几个小时!

一个表中的PK是utf8,另一个表中的PK是utf8_unicode_ci!

当使用MyISAM引擎创建父表时,我也遇到了同样的问题。这是一个愚蠢的错误,我用:

ALTER TABLE parent_table ENGINE=InnoDB;

我在Laravel 5.1迁移Schema Builder到MariaDB 10.1时也遇到了同样的问题。

问题是我在设置列时输入了unsigned而不是unsigned(s字母不见了)。

修复后,错别字为我修复。