MySQL查询时报错Illegal mix of collations
1.具体场景
两张表分别为:
CREATE TABLE `tb_user` (
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '用户编号(自增字段)',
`userName` varchar(32) NOT NULL DEFAULT '' COMMENT '用户昵称',
# ...
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1DEFAULT CHARSET=utf8 COMMENT='用户表';
CREATE TABLE `tb_sms_message` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`tel` varchar(255) CHARACTER SET utf8 COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '手机号',
# ...
PRIMARY KEY (`id`),
) ENGINE=InnoDB AUTO_INCREMENT=1DEFAULT CHARSET=utf8;
报错信息如下:
Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='
2.查询SQL
SELECT * FROM `tb_sms_message`
where tel not IN (select userName from tb_user);
3.原因分析
两个关联的字段的collate不一致,无法直接关联。
这里我们可以对字段的校对集转化为一致:
CONVERT(tel USING utf8) COLLATE utf8_general_ci
修改后的SQL:
SELECT * FROM `tb_sms_message`
where CONVERT(tel USING utf8) COLLATE utf8_general_ci not IN (select userName from tb_user);
网上搜了挺多的,但是真正提到我这个问题的解决方式:
http://www.cnblogs.com/mrma/p/3440992.html