笔记-mysql修改引擎和字符集排序规则

背景:

中途进的项目组,有部分表的引擎是MyISAM,然后字符集是utf8mb4没错,但是排序规则是utf8mb4_unicode_ci

需要批量把引擎换成InnoDB,把排序规则换成utf8mb4_general_ci

 

 

1、下面的sql可以把数据库名称为”schemaName“数据库所有引擎不是InnoDB的表搜索出来

SELECT
    table_name,
    table_schema,
  ENGINE 
FROM
    information_schema.TABLES 
WHERE
    ENGINE != 'InnoDB' 
    AND table_schema NOT IN ( 'mysql', 'information_schema', 'performance_schema' ) and  table_schema = 'schemaName'

然后下面的sql可以修改表table_name的引擎为InnoDB

ALTER TABLE table_name ENGINE=InnoDB;

 

把上面两条sql合在一起,改造一下:

SELECT
    CONCAT('alter table ',table_name,' ENGINE=InnoDB;')
FROM
    information_schema.TABLES 
WHERE
    ENGINE != 'innodb' 
    AND table_schema NOT IN ( 'mysql', 'information_schema', 'performance_schema' ) and  table_schema = 'schemaName'

 

执行一下改造之后的sql,拿到结果,批量执行,就可以把所有非InnoDB的改成InnoDB

 

有个小插曲,有两张表执行不成功,会报以下错误

#1031 - Table Storage Engine For '' Doesn't Have This Option

百度了应该是因为原表是低版本的mysql创建的脚本(项目所用版本为5.7.29)

需要在执行修改引擎的语句前修改ROW_FORMAT,即执行一下语句

ALTER TABLE table_name ROW_FORMAT = COMPACT;

这里有个知识点,如果联表查询,关联得外键得字符集得排序结果不一样会报以下得错误:

Illegal mix of collations (utf8mb4_unicode_ci,IMPLICIT) and (utf8mb4_general_ci,IMPLICIT) for operation '='

 

2、批量修改字符集和排序规则,把”schemaName“替换成自己的数据库

SELECT
    CONCAT( 'ALTER TABLE ', TABLE_NAME, ' CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;' ) 
FROM
    information_schema.TABLES 
WHERE
    ENGINE != 'innodb' 
    AND table_schema NOT IN ( 'mysql', 'information_schema', 'performance_schema' ) 
    AND table_schema = 'schemaName'

得到执行结果,复制出来,再批量执行即可

修改字符集和排序规则得语句:

ALTER TABLE table_name CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;

 

你可能感兴趣的:(mysql)