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


当前回答

我的情况是,我在参考栏上有一个错别字:

MariaDB [blog]> alter table t_user add FOREIGN KEY ( country_code ) REFERENCES t_country ( coutry_code );
ERROR 1005 (HY000): Can't create table `blog`.`t_user` (errno: 150 "Foreign key constraint is incorrectly formed")

错误消息非常神秘,我已经尝试了所有的方法——验证列的类型、排序规则、引擎等。

我花了一段时间才注意到这个错字,修复后一切都很好:

MariaDB [blog]> alter table t_user add FOREIGN KEY ( country_code ) REFERENCES t_country ( country_code );
Query OK, 2 rows affected (0.039 sec)              
Records: 2  Duplicates: 0  Warnings: 0

其他回答

试着运行以下命令:

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;

这个问题很容易解决

例如:你有两个表的名字用户和帖子,你想创建外键在帖子表和你使用phpMyAdmin

1)在post表中添加新列 (名称:use_id |类型:类似用户表中的id |长度:类似用户表中的id |默认值:NULL |属性:unsigned | index: index)

2)在结构标签进入关系视图 (约束名称:自动设置由phpmyAdmin |列名称:select user_id |表:用户|键:id,…)

它被简单地解决了

Javad mosavi伊朗/urmia

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

表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的数据类型必须为增量

我也有同样的问题。

问题是参考列不是主键。

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

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

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

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