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


当前回答

我在Symfony 2.8上也遇到了同样的问题。

我一开始没有得到它,因为外键的int长度等没有类似的问题。

最后,我必须在项目文件夹中执行以下操作。(服务器重启不起作用!)

应用程序/控制台学说:缓存:clear-metadata 应用程序/控制台学说:缓存:clear-query 应用程序/控制台学说:缓存:明确的结果

其他回答

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

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

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

甚至我在mysql和libase上也遇到了同样的问题。 这就是问题所在: 要引用其他表的列的表在数据类型或数据类型大小方面都不同。

Error appears in below scenario:
Scenario 1:
Table A has column id, type=bigint
Table B column referenced_id type varchar(this column gets the value from the id column of Table A.)
Liquibase changeset for table B:

    <changeset id="XXXXXXXXXXX-1" author="xyz">
            <column name="referenced_id" **type="varchar"**>
        </column>
            </changeset>
    <changeSet id="XXXXXXXXXXX-2" author="xyz">
                <addForeignKeyConstraint constraintName="FK_table_A"
                    referencedTableName="A" **baseColumnNames="referenced_id**"
                    referencedColumnNames="id" baseTableName="B" />
    </changeSet>

Table A changeSet:

    <changeSet id="YYYYYYYYYY" author="xyz">
     <column **name="id"** **type="bigint"** autoIncrement="${autoIncrement}">
                    <constraints primaryKey="true" nullable="false"/>
                </column>
    </changeSet>

Solution: 
correct the type of table B to bigint because the referenced table has type bigint.

Scenrario 2:
The type might be correct but the size might not.
e.g. :
Table B : referenced column type="varchar 50"
Table A : base column type ="varchar 255"

Solution change the size of referenced column to that of base table's column size.

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

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

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

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

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

我也有同样的问题,但我解决了。

只要确保列'ID'在'table1'有唯一的索引!

当然,这两个表中'ID'和'IDFromTable1'的列的类型和长度必须相同。但是你已经知道了。