在日常工作中經(jīng)常會出現(xiàn)數(shù)據(jù)庫表空間不夠的情況,需要對大量臨時表進(jìn)行清理,記錄一般執(zhí)行的如下操作。
介紹一下information_schema是Mysql用于元數(shù)據(jù)的內(nèi)部數(shù)據(jù)庫,記錄了數(shù)據(jù)庫名,表名,列名和訪問權(quán)限等信息,如下如所示。

information_schema庫中內(nèi)容
查看數(shù)據(jù)庫、表占用空間情況
- 切換到information_schema庫命令:
use information_schema;
- 查看所有數(shù)據(jù)庫的大小,以MB為單位,根據(jù)換算關(guān)系自定義:
select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables;
- 查看指定數(shù)據(jù)庫的大小,即在上一條命令的基礎(chǔ)上加上數(shù)據(jù)庫名稱作為篩選條件:
select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='數(shù)據(jù)庫名';
- 查看指定數(shù)據(jù)庫、指定表的占用空間大?。?/li>
select concat(round(sum(data_length/1024/1024),2),'MB') as data from tables where table_schema='數(shù)據(jù)庫名' and table_name='表名';
批量刪除數(shù)據(jù)庫下面的表
- 首先通過select命令生成要刪除的表sql語句,加上table_name的篩選條件刪除指定表:
select concat('drop table ',table_name,';') from information_schema.`TABLES` WHERE table_schema='數(shù)據(jù)庫名' and table_name='表名';
執(zhí)行結(jié)果如下:

select語句執(zhí)行結(jié)果
- 批量執(zhí)行sql語句,方便批量刪除數(shù)據(jù)表(刪庫需謹(jǐn)慎!)
drop table templ6_0_8512;
drop table templ7_0_5850;
drop table templ7_0_8512;
drop table templ8_0_5850;
drop table templ8_0_8512;
drop table templ9_0_5850;
drop table templ9_0_8512;
drop table template0_5850;
drop table template0_8512;
drop table templh1_5850;
drop table templh1_8512;
執(zhí)行結(jié)果:

刪除表操作