mysql - 数据库引擎的条件更改

标签 mysql

我想将数据库的表格式更改为 InnoDB。但我只希望在表格式还不是 InnoDB 时运行该操作。

如果执行以下命令,如果表格式已经是 InnoDB,则会一次又一次地启动耗时操作(类似于修复):

ALTER TABLE `MyTable` ENGINE InnoDB;

如果目标格式已经是 InnoDB,您是否可以为这种情况插入一个条件,以便操作运行得更快?

我在想类似的事情:

ALTER TABLE `MyTable` ENGINE InnoDB WHERE ENGINE != 'InnoDB';
ALTER TABLE IGNORE `MyTable` ENGINE InnoDB;

最佳答案

您可以使用information_schema.TABLES,生成脚本:

set @db_schema = 'test';
set @alter_query = 'alter table `{table}` engine=innodb;';

select group_concat(replace(
    @alter_query,
    '{table}',
    replace(t.TABLE_NAME, '`', '``')
) separator '\n') as script
from information_schema.TABLES t
where t.TABLE_SCHEMA = @db_schema
  and t.ENGINE = 'MyISAM';

然后你需要复制结果并执行它。

Demo

更新

如果需要一次性执行,可以定义一个游标在information_schema.TABLES上的存储过程并执行:

drop procedure if exists tmp_alter_myisam_to_innodb;
delimiter //
create procedure tmp_alter_myisam_to_innodb(in db_name text)
begin
    declare done int default 0;
    declare tbl text;
    declare cur cursor for 
        select t.TABLE_NAME
        from information_schema.TABLES t
        where t.TABLE_SCHEMA = db_name
          and t.ENGINE = 'MyISAM';
    declare continue handler for not found set done = 1;
    open cur;
    fetch_loop: loop
        fetch cur into tbl;
        if done then
            leave fetch_loop;
        end if;
        set @stmt = 'alter table `{table}` engine=innodb;';        
        set tbl = replace(tbl, '`', '``');
        set @stmt = replace(@stmt, '{table}', tbl);
        prepare stmt from @stmt;
        execute stmt;
        deallocate prepare stmt;
    end loop;
    close cur;
end //
delimiter ;

call tmp_alter_myisam_to_innodb('my_db');
drop procedure tmp_alter_myisam_to_innodb;

关于mysql - 数据库引擎的条件更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55467915/

相关文章:

mysql - SQL - where 子句中的未知列

php - 在 PHP 中显示 mysql SUM

java - 获取 http 响应 PHP 和 ANDROID

mysql - 将数据库中的两个字符串连接在一起

android - 我的 RecyclerView Activity 显示空白 Activity

mysql - 我可以使这个 mySQL 查询更快吗?

php - mySQL 查询不工作

mysql - 使用 COUNT 过滤标签

mysql - 使用 node.js 在 mysql 中插入几何值

mysql - 自动生成表并按名称分组值并获取多个值