MySQL查看数据库大小,表占用空间
前言
磁盘快满了,不知道哪个库哪个表占空间大。本文教你查MySQL数据库和表的大小。
一、查看所有数据库大小
SELECT
table_schema AS '数据库名',
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS '大小(MB)'
FROM information_schema.tables
GROUP BY table_schema
ORDER BY SUM(data_length + index_length) DESC;
输出:
| 数据库名 | 大小(MB) |
|---|---|
| mydb | 512.34 |
| test | 128.56 |
| mysql | 10.24 |
二、查看某个数据库的所有表大小
SELECT
table_name AS '表名',
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS '大小(MB)',
table_rows AS '行数'
FROM information_schema.tables
WHERE table_schema = 'mydb'
ORDER BY (data_length + index_length) DESC;
把 mydb 换成你的数据库名。
三、查看单个表大小
SELECT
table_name AS '表名',
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 = 'mydb' AND table_name = 'users';
四、查看所有表大小(按大小排序)
SELECT
table_schema AS '数据库',
table_name AS '表名',
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS '大小(MB)',
table_rows AS '行数'
FROM information_schema.tables
ORDER BY (data_length + index_length) DESC
LIMIT 20;
只看前20大的表。
五、用命令行查看
查看数据目录
du -sh /var/lib/mysql/
查看某个库的大小
du -sh /var/lib/mysql/mydb/
查看所有库的大小
du -sh /var/lib/mysql/*/
六、常用场景
场景1:磁盘满了,找大表
SELECT
table_schema AS '数据库',
table_name AS '表名',
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS '大小(MB)'
FROM information_schema.tables
ORDER BY (data_length + index_length) DESC
LIMIT 10;
找出最大的10个表。
场景2:表很大,想知道数据和索引各占多少
SELECT
table_name AS '表名',
ROUND(data_length / 1024 / 1024, 2) AS '数据(MB)',
ROUND(index_length / 1024 / 1024, 2) AS '索引(MB)'
FROM information_schema.tables
WHERE table_schema = 'mydb';
场景3:清理无用数据,释放空间
删了很多数据,但磁盘空间没释放。
原因: InnoDB删数据后不会自动释放磁盘空间。
解决: 优化表:
OPTIMIZE TABLE users;
常见坑
坑1:table_rows不准
InnoDB的table_rows是估算值,不是精确值。
原因: InnoDB是多版本的,统计信息不精确。
解决: 要精确行数用 SELECT COUNT(*) FROM 表名;
坑2:删了数据空间没释放
DELETE删了很多行,但文件大小没变。
原因: InnoDB的表空间不会自动收缩。
解决: OPTIMIZE TABLE 表名; 或者重建表。
坑3:临时表占空间
performance_schema等系统库也占空间。
解决: 正常现象,不用管。
坑4:ibdata1文件很大
共享表空间文件很大,但不知道里面是什么。
原因: 所有InnoDB表都存在一个文件里。
解决: 开 innodb_file_per_table,每个表独立文件。
总结
常用查询:
- 查所有库大小:
GROUP BY table_schema - 查某库所有表:
WHERE table_schema='库名' - 查某表大小:
WHERE table_schema='库名' AND table_name='表名'
记住: 磁盘满了先查information_schema.tables找大表。
遇到问题加QQ23979811 协助处理