格式错误mysql_mysql外键约束格式错误

bd96500e110b49cbb3cd949968f18be7.png

I have two tables, table1 is the parent table with a column ID and table2 with a column IDFromTable1 (not the actual name) when I put a FK on IDFromTable1 to ID in table1 I get the error Foreign key constraint is incorrectly formed error. I would like to delete table 2 record if table1 record gets deleted. Thanks for any help

ALTER TABLE `table2`

ADD CONSTRAINT `FK1`

FOREIGN KEY (`IDFromTable1`) REFERENCES `table1` (`ID`)

ON UPDATE CASCADE

ON DELETE CASCADE;

Let me know if any other information is needed. I am new to mysql

解决方案

I ran into this same problem with HeidiSQL. The error you receive is very cryptic. My problem ended up being that the foreign key column and the referencing column were not of the same type or length.

The foreign key column was SMALLINT(5) UNSIGNED and the referenced column was INT(10) UNSIGNED. Once I made them both the same exact type, the foreign key creation worked perfectly.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MySQL中,设置外键后更改编码格式可能会导致一些问题。根据引用\[1\],在某些情况下,当外键使用不同的编码格式时,可能会出现错误。例如,如果主表使用"varchar(36)DEFAULT NULL"定义外键,而从表使用"varchar(36)COLLATE utf8mb4_general_ci DEFAULT NULL"定义外键,可能会导致错误。这是因为外键的编码格式不匹配。 为了解决这个问题,你可以按照引用\[2\]中的方法,在创建表时指定外键约束,并确保主表和从表使用相同的编码格式。例如,你可以使用以下语句创建表并指定外键约束: ```sql CREATE TABLE score ( id int(10) NOT NULL PRIMARY KEY auto_increment, sid INT(10), name varchar(50) DEFAULT NULL, subject varchar(50) DEFAULT NULL, score varchar(50) DEFAULT NULL, CONSTRAINT fk_sid FOREIGN KEY(sid) REFERENCES 主表名(主表的主键字段) ) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4; ``` 这样,主表和从表都将使用InnoDB引擎和utf8mb4编码格式。 如果你已经创建了表并且想要更改编码格式,你可以使用ALTER TABLE语句来添加外键约束,如引用\[3\]所示。但是,请注意,在更改编码格式之前,你需要确保所有的表都使用相同的编码格式。你可以使用SHOW TABLE STATUS LIKE table_name;来查看每个表的引擎和编码格式。 总之,当设置外键后更改编码格式时,你需要确保主表和从表使用相同的编码格式,并在创建表时或使用ALTER TABLE语句时指定外键约束。这样可以避免出现编码格式不匹配的错误。 #### 引用[.reference_title] - *1* *3* [关于sql:mysql外键约束格式错误](https://blog.csdn.net/weixin_36076151/article/details/116120838)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [MYSQL外键约束](https://blog.csdn.net/omaidb/article/details/129985930)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值