mysql - 更改字符集后无法添加外键约束

标签 mysql sql database foreign-keys

我有一个表,用于在应用程序中存储文本消息。我想添加使用表情符号的功能,但它们一直显示为? ? ? ?等等...在数据库中。我了解到我需要更改我的表的字符集,所以我运行了命令

ALTER TABLE 发布 CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin

但我收到此错误:错误代码:1832。无法更改列“user_id”:用于外键约束“posts_ibfk_2”

所以我放弃了 FK,然后运行命令,一切正常。但是现在,当我尝试读取 FK 时,我不断收到 1215 错误,提示我无法添加 FK 约束。

ALTER TABLE posts
ADD FOREIGN KEY (user_id)
REFERENCES users(id);

我尝试将字符集转换回原来的状态,但仍然无法添加 FK。我怎样才能把它加回来?

最佳答案

注意下面的粗体点,摘自 MySQL Docs :

Foreign key relationships involve a parent table that holds the central data values, and a child table with identical values pointing back to its parent. The FOREIGN KEY clause is specified in the child table. The parent and child tables must use the same storage engine.

Corresponding columns in the foreign key and the referenced key must have similar data types. The size and sign of integer types must be the same. The length of string types need not be the same. For nonbinary (character) string columns, the character set and collation must be the same.

When foreign_key_checks is enabled, which is the default setting, character set conversion is not permitted on tables that include a character string column used in a foreign key constraint.

基本上,改变子表中referencing字段的字符集和排序规则后;它与父表中引用 字段的字符集和排序规则不匹配。您需要确保它们都匹配。

所以,users表中id字段的Character Set和Collat​​ion应该是utf8mb4utf8mb4_bin 分别。我假设 id 列的数据类型是 VARCHAR(32)。您可以相应地更改它:

ALTER TABLE users 
MODIFY id VARCHAR(32) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin

关于mysql - 更改字符集后无法添加外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53158729/

相关文章:

mysql - 如何检查另一行是否存在值?

mysql - 我的 Where 条件没有返回表中的每一行,如何让它返回行?

mysql - 是否有 SQL 选择限定符来执行 Skip() 和 Take()

sql - Postgres : average user response time from interaction with a bot

c - 磁盘数据结构的体系结构

php - 在mysql中搜索字符串数组

mysql - 不将用户数据保存到 laravel 5.6 中的用户表

mysql - 跟踪电子商务访客和销售

MySQL 一对一关系

sql - UDA 生成错误,缓冲区大小不足