先贴一张图!
第一步,“很重要”
在mysql中,有一个创建之初自带的库information_schema
,这个库中包含着数据库相关信息,查询数据占用空间就是使用该库,所以首先进入这个库
-- 首先进入mysql系统库use information_schema;
第二步:查询
使用sum(DATA_LENGTH/1024/1024)
统计占用MB大小,分为两块,一个是DATA_LENGTH
—数据 、INDEX_LENGTH
—索引。
如下:
-- 查询数据库中所有数据占用空间SELECTconcat( round( sum( DATA_LENGTH / 1024 / 1024 ), 2 ), 'MB' ) AS DATA FROMTABLES;
-- 查询指定 数据库 的 指定表 数据占用空间SELECTconcat( round( sum( data_length / 1024 / 1024 ), 2 ), 'MB' ) AS DATA FROMTABLES WHEREtable_schema = '{your database}' AND table_name = '{your table name}';
-- 查询指定 数据库 的 指定表 索引占用空间SELECTconcat( round( sum( index_length / 1024 / 1024 ), 2 ), 'MB' ) AS DATA FROMTABLES WHEREtable_schema = '{your database}' AND table_name = '{your table name}';
第三步:拿来即用
两条润色后的sql,可以直接很清晰地查询 库 和 表占用的大小。只需要修改参数{your databse}
即可
PS:必须先执行第一步
-- 查询库中所有表的总和,分项列出select table_schema as '数据库', sum(table_rows) as '记录数', sum(truncate(data_length/1024/1024, 2)) as '数据容量(MB)', sum(truncate(index_length/1024/1024, 2)) as '索引容量(MB)' from information_schema.tables where table_schema='{your database}';
-- 查询库中每个表的空间占用,分项列出select table_schema as '数据库', table_name as '表名', table_rows as '记录数', truncate(data_length/1024/1024, 2) as '数据容量(MB)', truncate(index_length/1024/1024, 2) as '索引容量(MB)' from information_schema.tables where table_schema='{your database}' order by data_length desc, index_length desc;