如何使用外键更改 InnoDB 表中的字符集?

问题描述 投票:0回答:2

我有一组具有外键的 InnoDB 表,我想将这些表的默认字符集从

latin1_swedish_ci
更改为
utf8_general_ci
,我尝试运行以下查询:

ALTER TABLE test.PAYMENT DROP FOREIGN KEY PAYMENT_ibfk_1;

但是它给了我这个错误:

ERROR 1025 (HY000): Error on rename of './test/#sql-1fa_24f43' to './test/PAYMENT' (errno: 150)

我尝试通过 set 执行此更改

foreign_key_checks=0
;即使禁用按键,但仍然出现相同的错误。

mysql innodb collation
2个回答
4
投票

我通过从所有引用表和主表中删除外键解决了这个问题

 alter table test.PAYMENT drop foreign key PAYMENT_ibfk_1;
 alter table test.ORDER_DETAILS drop foreign key ordr_dets_ibfk_1;
 alter table test.TRANSACTION  drop foreign key transaction_ibfk_1;

后来更改了所有表格并更改了字符集

 alter table  test.PAYMENT CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; 
 alter table  test.TRANSACTION CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; 
 alter table  test.ORDER_DETAILS CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci; 

然后再次应用外键

alter table niclient.PAYMENT add foreign key PAYMENT_ibfk_1 (paymentTransId)  references `TRANSACTION` (`transId`) ON DELETE CASCADE;
alter table niclient.ORDER_DETAILS add foreign key ordr_dets_ibfk_1 (ordrDetTransId) REFERENCES `TRANSACTION` (`transId`) ON DELETE CASCADE;
alter table niclient.TRANSACTION add foreign key transaction_ibfk_1 (transCompId)  REFERENCES `COMPANY_DETAILS` (`compId`) ON DELETE CASCADE;

效果很好:-)


0
投票

如果您 100% 确定自己在做什么,

您最终可以评估使用 InnoDB 引擎上提供的禁用外键检查的选项。

示例:

SET FOREIGN_KEY_CHECKS=0;

ALTER TABLE ...;
ALTER TABLE ...;
ALTER TABLE ...;
ALTER TABLE ...;

SET FOREIGN_KEY_CHECKS=1;

相关文档:

https://mariadb.com/docs/server/ref/mdb/system-variables/foreign_key_checks/

像往常一样,在做此类事情之前先做好备份。

© www.soinside.com 2019 - 2024. All rights reserved.