mysql查询报错java.sql.SQLException: Illegal mix of collations for operation ‘UNION‘
1.场景
需要写一个sql,需要合并 从四张表查询查询出来的结果,需要用到 UNION ALL 对查询结果进行合并
2.sql
-- 从 unit 表中查询
select id, name, '1' as type
from unit
where name like concat('%', #{name}, '%')
UNION ALL
-- 从 system 表中查询
select id, name, '2' as type
from system
where name like concat('%', #{name}, '%')
UNION ALL
-- 从 equipment 表中查询
select id, name, '3' as type
from equipment
where name like concat('%', #{name}, '%')
UNION ALL
-- 从 measuring_point 表中查询
select id, name, '4' as type
from measuring_point
where name like concat('%', #{name}, '%')
3.查询报错
java.sql.SQLException: Illegal mix of collations for operation 'UNION'
4.检查4张建表语句的排序规则是否一致
SHOW FULL COLUMNS FROM unit;
SHOW FULL COLUMNS FROM system;
SHOW FULL COLUMNS FROM equipment;
SHOW FULL COLUMNS FROM measuring_point;
CREATE TABLE `template_config_unit` (
`id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键',
`template_name` varchar(255) COLLATE utf8mb4_general_ci NOT NULL COMMENT '机组模板名称',
`code` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci DEFAULT NULL COMMENT '编码',
`type` int DEFAULT NULL COMMENT '机组类型(1:锅炉专业, 2:汽机专业, 3:电气专业, 4:环化专业)'
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=227 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci COMMENT='机组表';
重点关注
ENGINE=InnoDB AUTO_INCREMENT=227 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci
5.本人遇到的问题 是排序规则不一致造成的
6.解决方案
修改表的排序规则
ALTER TABLE unit CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE system CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE equipment CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
ALTER TABLE measuring_point CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
7.最后
问题解决