MySQL中查看表大小应使用information_schema.tables查询data_length+index_length,它反映数据与索引总占用空间(单位字节),再换算为MB;InnoDB行数为估算值,真实文件大小需结合ls -lh验证碎片情况。
在 MySQL 中查看表大小,主要是为了了解数据文件和索引文件实际占用的磁盘空间,尤其在排查磁盘告警、优化大表或评估归档需求时非常实用。注意:表大小 ≠ 表中数据行数 × 单行平均长度,它受存储引擎(InnoDB/MyISAM)、行格式、碎片、索引数量、空闲空间等多种因素影响。
推荐使用 information_schema.tables,这是最通用且准确的方式:
SELECT table_name AS `表名`, ROUND((data_length + index_length) / 1024 / 1024, 2) AS `大小(MB)`, ROUND(data_length / 1024 / 1024, 2) AS `数据(MB)`, ROUND(index_length / 1024 / 1024, 2) AS `索引(MB)`, table_rows AS `行数` FROM information_schema.tables WHERE table_schema = 'your_database_name' AND table_name = 'your_table_name';
data_length:主数据存储占用(如 InnoDB 的聚簇索引页、MyISAM 的 .MYD 文件)index_length:所有二级索引占用(.MYI 文件或 InnoDB 的辅助索引页)1024² 转为 MB 更直观table_rows 是估算值(来自统计信息),不一定完全精确快速定位“磁盘大户”,便于优先优化:
SELECT table_name AS `表名`, ROUND((data_length + index_length) / 1024 / 1024, 2) AS `大小(MB)`, ROUND(data_length / 1024 / 1024, 2) AS `数据(MB)`, ROUND(index_length / 1024 / 1024, 2) AS `索引(MB)` FROM information_schema.tables WHERE table_schema = 'your_database_name' AND table_type = 'BASE TABLE' ORDER BY data_length + index_length DESC LIMIT 10;
AND table_type = 'BASE TABLE' 排除视图(view)干扰data_length + index_length 降序,确保真正占空间的表排在前面LIMIT 10 改成 LIMIT 20 或去掉,看全部information_schema 提供的是逻辑大小估算;若想确认磁盘上 .ibd 文件真实大小,需结合操作系统命令(适用于独立表空间 innodb_file_per_table=ON):
SELECT file_name FROM information_schema.innodb_datafiles WHERE file_name LIKE '%your_table_name%';SELECT table_name, engine, row_format FROM information_schema.tables... 确认是 InnoDB + 独立表空间)/var/lib/mysql/your_database_name/),执行:ls -lh your_table_name.ibd
ls -lh 结果与 information_schema 中的 data_length + index_length:OPTIMIZE TABLE your_table_name;(注意锁表风险)不同引擎计算逻辑一致,但底层含义不同:
data_length ≈ .MYD 文件大小,index_length ≈ .MYI 文件大小,基本等于磁盘占用innodb_file_per_table=ON(默认),每张表有独立 .ibd 文件,data_length + index_length 接近该文件大小OFF,所有表共享 ibdata1,此时 information_schema 中的大小仍有效,但无法对应到单个文件data_length