【问题标题】:mysql bulk drop tables where table_name like '%phrase'mysql 批量删除表,其中 table_name 像 '%phrase'
【发布时间】:2015-10-31 03:33:45
【问题描述】:

好的,我有大约 68,000 个表需要删除一个特定的短语。当我运行命令时:

SHOW TABLES where table_name like '%phrase';

我得到了我需要的所有结果,但我尝试运行以下代码,它只摆脱了 68,000 个中的 6 个:

SET @temp_statement = NULL;
SELECT 
  GROUP_CONCAT(table_schema, '.`', table_name, '`') INTO @temp_statement 
FROM
  (
  SELECT
    table_schema, table_name
  FROM
    information_schema.tables 
  WHERE
    table_schema = 'db_name_goes_here' AND table_name LIKE 'table_base_name_here_%'
  LIMIT 10 -- a limit to avoid exceeding group_concat_max_len
  ) JUST_A_TEMP_NAME;

-- up to this point, @temp_statement holds something like this:
-- mydb.`table1`,mydb.`table2`,...,mydb.`tableN`

SET @temp_statement = CONCAT('DROP TABLE ', @temp_statement);
SELECT @temp_statement; -- let's see the SQL statement before executing it
PREPARE stmt1 FROM @temp_statement;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
SET @temp_statement = NULL; -- clean up

【问题讨论】:

    标签: mysql sql


    【解决方案1】:

    您可以分两步完成:

    第一次执行:

    SELECT CONCAT('DROP ', table_schema, '.', table_name, ';') statement
    FROM   information_schema.tables 
    WHERE  table_schema = 'db_name_goes_here'
    AND    table_name LIKE 'table_base_name_here_%';
    

    输出将如下所示:

    statement
    --------------------------------------------------------
    DROP myschema.mytable1;
    DROP myschema.mytable2;
    

    然后获取输出,并作为一批 SQL 语句再次执行。

    在我看来是最实用的方法。

    【讨论】:

    • 好吧——这似乎是合理而直接的。我的第二个后续问题:我注意到当我删除表时,删除的表被存储在某个地方。所以当我删除 1gb 的表时——它们占用了另外 gb 的空间。我怎样才能阻止这种情况并取回所有“丢弃的表”存储空间。
    • 这完全是另一个问题。你可能会找到答案here
    猜你喜欢
    • 2012-06-04
    • 2012-06-18
    • 1970-01-01
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2012-03-03
    • 2013-01-08
    • 1970-01-01
    相关资源
    最近更新 更多