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


当前回答

或者您可以使用DBDesigner4,它具有图形界面来创建数据库并使用FK链接它们。右键单击您的表并选择“复制表SQL创建”,这将创建代码。

其他回答

我也犯了同样的错误,我发现在我自己的案例中,一张表是MyISAM,另一张是INNO。一旦我把MyISAM表切换到INNO。这解决了问题。

我在使用HeidiSQL时也遇到了同样的问题。您收到的错误非常神秘。我的问题是外键列和引用列的类型或长度不相同。

外键列是SMALLINT(5) UNSIGNED,引用列是INT(10) UNSIGNED。一旦我将它们都设置为完全相同的类型,外键的创建就会完美地工作。

我正在使用HeidiSQL,为了解决这个问题,我必须在引用表中创建一个索引,其中所有列都被引用。

试着运行以下命令:

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;

我也有同样的问题。

问题是参考列不是主键。

把它设为主键,问题就解决了。