SQL报错#1267:utf8mb4排序规则不兼容问题求助
问题解决:SQL排序规则冲突报错
问题描述
原SQL运行正常,添加CASE语句后触发报错:
#1267 - Illegal mix of collations (utf8mb4_general_ci,COERCIBLE) and (utf8mb4_unicode_ci,COERCIBLE) for operation '='
已将数据库和表的排序规则改为utf8mb4_general_ci,但错误仍存在,涉及的USFacilitywithType和USFacilityPriceWithDisc均为视图,需求是:Type 3类型用视图价格计算折扣价,其他类型直接用原价。
报错原因
报错源于字符串比较操作(JOIN条件里的Category = Type、CASE里的Category='Type 3')中,参与比较的字段/字符串排序规则不匹配。视图的字段排序规则是创建时继承自基表的,即使后续修改了基表或数据库的默认排序规则,已存在的视图不会自动更新字段的排序规则,导致冲突。
解决方案
方案1:重建视图(彻底解决)
- 先确认视图依赖的所有基表中,
Category和Type字段的排序规则均为utf8mb4_general_ci,若不一致,先修改基表字段的排序规则:
ALTER TABLE 基表名 MODIFY COLUMN Category VARCHAR(xxx) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci; ALTER TABLE 基表名 MODIFY COLUMN Type VARCHAR(xxx) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
- 删除原视图后重新创建:
DROP VIEW IF EXISTS ustoreat_ecomm.USFacilitywithType; DROP VIEW IF EXISTS ustoreat_ecomm.USFacilityPriceWithDisc; -- 重新执行创建视图的SQL语句
方案2:临时规避(快速生效)
在所有字符串比较的位置显式指定排序规则,修改后的完整SQL如下:
select `USFacilitywithType`.`unitno` AS `Unitno`,`USFacilitywithType`.`description` AS `description`, `USFacilitywithType`.`size` AS `size`,`USFacilitywithType`.`netprice` AS `netprice`, case when `USFacilitywithType`.`Category` COLLATE utf8mb4_general_ci = 'Type 3' COLLATE utf8mb4_general_ci then round(`USFacilitywithType`.`netprice` * `USFacilityPriceWithDisc`.`PriceLevel`,2) else round(`USFacilitywithType`.`netprice` * 1) end AS `Discounted Price`, `USFacilitywithType`.`Maintenance` AS `Maintenance`,`USFacilitywithType`.`zone` AS `Zone`, case when `USFacilitywithType`.`unitno` like '%/A/%' then 'Aircon' else 'Non-Aircon' end AS `Type` from (`ustoreat_ecomm`.`USFacilitywithType` join `ustoreat_ecomm`.`USFacilityPriceWithDisc` on(`USFacilitywithType`.`Category` COLLATE utf8mb4_general_ci = `USFacilityPriceWithDisc`.`Type` COLLATE utf8mb4_general_ci) )
内容的提问来源于stack exchange,提问作者Effendi Baba
相关产品推荐
相关产品推荐

