一、前言
在我们平时工作中,如果一个业务运行很久了,可能会需要我们去看看这块业务产生的数据量有多大,比如这个业务所使用的数据库存储空间都使用了多少个G了,哪一张数据表才是大表,下面整理了一些可以拿来即用的SQL以供小伙伴们参考。
二、如何在 MySQL 数据库中,查询数据库、表、索引的容量大小?
在每个 MySQL 实例中,都有一个独立的 information_schema
库,它是自带的库,记录着这个 MySQL 实例中所有数据库的元数据、统计信息、以及有关 MySQL 的访问权限信息。其中就包括了所有数据库、表、索引的详细信息。

在information_schema
库下有一个名为TABLES的视图,通过这个视图,可获取指定库的表名、引擎、行数等元数据,下面我们直接看示例sql:
1.查看MySQL中所有数据库的容量大小
mysql
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)',
sum(truncate(DATA_FREE/1024/1024, 2)) as '碎片占用(MB)'
from information_schema.tables
group by table_schema
order by sum(data_length) desc, sum(index_length) desc;

data_length、index_length、DATA_FREE等字段,所存储的容量信息单位是字节,所以我们要除以 2个1024把字节转化为可读性更强的MB。
上面只截了两个数据库的信息出来,一个数据库的总大小就是数据容量和索引容量之和。
2.查看MySQL指定数据库的容量大小
sql
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)',
sum(truncate(DATA_FREE/1024/1024, 2)) as '碎片占用(MB)'
from information_schema.tables
where table_schema='ry' -- 这里ry替换成你自己的数据库名
order by data_length desc, index_length desc;
3.查看MySQL指定数据库的表大小
sql
SELECT
table_name as '表名',
(table_rows) as '记录数',
round(data_length/1024/1024, 2) as '数据容量(MB)',
round(index_length/1024/1024, 2) as '索引容量(MB)'
from information_schema.tables
where table_schema='ry'-- 你要查哪个数据库中的表
order by data_length desc, index_length desc;
4.查看指定表的详细空间信息
sql
SELECT
table_name as '表名',
engine as '存储引擎',
table_rows as '记录数',
*round*(data_length/1024/1024, 2) as '数据容量(MB)',
*round*(index_length/1024/1024, 2) as '索引容量(MB)'
from information_schema.tables
where table_schema='ry' -- 你要查哪个数据库
and table_name = 'seat';-- 你要查哪个数据库中的哪个表
通过以上方法,小伙伴们可以全面了解MySQL数据库中各个表的空间占用情况,为数据库优化和维护提供数据支持。