MySQL升级为8.0版本时,之前版本的字符集往往是不同的,需要校正。
执行下面的三个SQL语句的查询结果,可以从库、表、列三个层面对字符集进行校正。
-
库
select concat('alter database ', schema_name, ' default character set utf8mb4 collate utf8mb4_general_ci;') from information_schema.schemata where schema_name not in ('sys', 'mysql', 'performance_schema', 'information_schema') and (lower(default_collation_name) != 'utf8mb4_general_ci' or lower(default_character_set_name) != 'utf8mb4');
-
表
select concat('alter table ', table_schema, '.', table_name, ' default character set utf8mb4 collate = utf8mb4_general_ci;') from information_schema.tables where table_schema not in ('sys', 'mysql', 'performance_schema', 'information_schema') and table_type = 'BASE TABLE' and lower(table_collation) != 'utf8mb4_general_ci';
-
列
set group_concat_max_len = 10240; select concat(c1, c2, ';') from (select c1, group_concat(c2) c2 from (select concat('alter table ', t1.table_schema, '.', t1.table_name) c1, concat(' modify ', '`', t1.column_name, '` ', t1.data_type, if(t1.data_type in ('varchar', 'char'), concat('(', t1.character_maximum_length, ')'), ''), if(t1.column_default != '', concat(' default \'', t1.column_default, '\''), ''), ' collate utf8mb4_general_ci', if(t1.is_nullable = 'NO', ' not null', ' null'), ' comment ', '''', t1.column_comment, '''') c2 from information_schema.columns t1, information_schema.tables t2 where t1.table_schema = t2.table_schema and t1.table_name = t2.table_name and t2.table_type = 'BASE TABLE' and (lower(t1.collation_name) != 'utf8mb4_general_ci' or lower(t1.character_set_name) != 'utf8mb4') and t1.table_schema not in ('sys', 'mysql', 'performance_schema', 'information_schema')) t1 group by c1) t;