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

时间:2015-04-24 10:34:39

标签: mysql innodb collation

我有一组具有外键的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)

我尝试通过设置foreign_key_checks=0执行此更改;甚至通过禁用键但仍然得到相同的错误。

1 个答案:

答案 0 :(得分:2)

我通过从所有引用表和主表中删除外键来解决它

 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;

完美无缺: - )