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


当前回答

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

ALTER TABLE parent_table ENGINE=InnoDB;

其他回答

定义外键的语法是非常宽容的,但对于任何其他人来说,外键必须“具有相同类型”的事实甚至适用于排序,而不仅仅是数据类型、长度和位签名。

并不是说你会在你的模型中混合排序规则(你会吗?),但如果你这样做了,确保你的主键和外键字段在phpmyadmin或Heidi SQL或其他你使用的工具中具有相同的排序规则类型。

希望这能帮你省下我花在试错上的4个小时。

试着运行以下命令:

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;

我有同样的问题,两列都是INT(11) NOT NULL,但我不能创建外键。 我必须禁用外键检查才能成功运行:

SET FOREIGN_KEY_CHECKS=OFF;
ALTER TABLE ... ADD CONSTRAINT ...
SET FOREIGN_KEY_CHECKS=ON;

希望这能帮助到一些人。

Mysql错误文本没有那么多的帮助,在我的情况下,列有“不空”约束,所以“删除设置空”是不允许的

我面临这个问题,当你把主键放在不同的数据类型,比如:

表1:

 Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->string('product_name');
        });

表2:

Schema::create('brands', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('brand_name');
        });

第二个表id的数据类型必须为增量