我有两个表,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的新手


当前回答

我在这里遗漏的另一个解决方案是,在创建约束的表中,引用表的每个主键都应该有一个带有外键的条目。

其他回答

谢谢S Doerin:

“只是为了完成。 如果你有一个VARCHAR(..)外键,并且被引用的表的字符集与引用它的表的字符集不同,也可能会出现这个错误。 例如,Latin1表中的VARCHAR(50)与UTF8表中的VARCHAR(50)不同。

我解决了这个问题,改变了表格的字符类型。 创建的是latin1,正确的是utf8。

添加下一行。 默认字符集= utf8;

如果你的表是Myisum,新表是InoDb,你是Note Foreign 您必须将MyIsum表更改为InoDb

在Laravel中,当您在引用table2的迁移之后又迁移了外键table table1时,也会出现这个问题。

您必须保留迁移的顺序,以便外键特性能够正常工作。

database/migrations/2020_01_01_00001_create_table2_table.php
database/migrations/2020_01_01_00002_create_table1_table.php

应该是:

database/migrations/2020_01_01_00001_create_table1_table.php
database/migrations/2020_01_01_00002_create_table2_table.php

试着运行以下命令:

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;

我刚才也遇到了同样的问题。在我的例子中,我所要做的就是确保我在外键中引用的表必须在当前表之前创建(在代码的前面)。因此,如果你引用一个变量(x*5),系统应该知道x是什么(x必须在前面的代码行中声明)。这解决了我的问题,希望它能帮助其他人。