好的,我放弃了。我已经陷入这个错误两天了,需要帮助。
免责声明:我需要帮助改进这个问题,并尽力描述问题的关键、我已经采取的解决问题的措施以及我搜索解决方案时阅读的博客文章和文档。
问题(也在下文中提出):
所以问题是,为什么相同的查询在从Rails而不是从mysql命令行运行时表现不同?具体来说,“(utf8_general_ci,COERCIBLE)”从何而来?
问题描述:Autoresponder.find_by(keyword: '')
会失败并显示以下错误:
ActiveRecord::StatementInvalid: Mysql2::Error: Illegal mix of collations
(utf8mb4_unicode_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE)
for operation '=':
SELECT `autoresponders`.*
FROM `autoresponders`
WHERE `autoresponders`.`keyword` = ''
LIMIT 1
自动回复器
是一个具有属性关键字
的模型。
我读到需要指定我的排序规则。所以我尝试了以下代码:
Autoresponder.where('keyword collate utf8mb4_unicode_ci = ?', '')
并收到以下错误:
Illegal mix of collations
(utf8mb4_unicode_ci,EXPLICIT) and (utf8_general_ci,COERCIBLE)
for operation '=':
SELECT `autoresponders`.*
FROM `autoresponders`
WHERE (keyword collate utf8mb4_unicode_ci = '')
那只是将排序规则从IMPLICIT更改为EXPLICIT。
我尝试在Sequel Pro中运行查询,它可以正常工作(使用或不使用collate关键字都可以)。为了清晰起见,这是查询:
SELECT `autoresponders`.*
FROM `autoresponders`
WHERE (keyword collate utf8mb4_unicode_ci = '');
SELECT `autoresponders`.*
FROM `autoresponders`
WHERE (keyword = ' ');
而且它还起作用!查询运行时没有出现错误。我也运行了mysql
,并能够在那里运行查询。但是当我将查询粘贴到mysql
命令行中时,我注意到了一些问题。它自动使用字符的Unicode名称,而不是实际字符。以下是在mysql命令行中观察到的查询:
SELECT `autoresponders`.*
FROM `autoresponders`
WHERE (keyword collate utf8mb4_unicode_ci ='\U+1F615');
这个查询有效。
问题是,为什么相同的查询在Rails中失败而在Sequel Pro中正常工作?具体来说,“(utf8_general_ci,COERCIBLE)”从哪里来,我该如何解决这个问题?
我认为它可能来自ActiveRecord,但在Rails控制台中运行 ActiveRecord :: Base.connection.collation
返回 utf8mb4_unicode_ci
这是我的数据库字符编码和排序变量(以及检索它们的查询)。
SHOW VARIABLES WHERE Variable_name LIKE 'character\_set\_%' OR Variable_name LIKE 'collation%';
character_set_client utf8mb4
character_set_connection utf8mb4
character_set_database utf8mb4
character_set_filesystem binary
character_set_results utf8mb4
character_set_server latin1
character_set_system utf8
collation_connection utf8mb4_unicode_ci
collation_database utf8mb4_unicode_ci
collation_server latin1_swedish_ci
以下是自动回复表的创建语法:
CREATE TABLE `autoresponders` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`keyword` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT '',
`body` varchar(191) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`provisioned_number_id` int(11) DEFAULT NULL,
`outgoing_provisioned_number_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci ROW_FORMAT=DYNAMIC;
背景: Rails 4.0.13,Mysql版本5.6.22-1+deb.sury.org〜precise + 1-log
这里是我迄今为止阅读过的一些博客文章和SO文章:
https://mathiasbynens.be/notes/mysql-utf8mb4 http://airbladesoftware.com/notes/fixing-mysql-illegal-mix-of-collations/ “SET CHARACTER SET utf8”是否必要? 使用(utf8_unicode_ci,IMPLICIT)和(utf8_general_ci,IMPLICIT)进行操作时出现了字符集混合错误。 Active Record中不区分大小写搜索 https://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_collation_server所有这些都促使我创建了这个梗:
![enter image description here](https://istack.dev59.com/oOHqh.webp)
真诚地,
一位筋疲力尽的开发人员。
谢谢。