第一步,首先进入mysql系统库
在mysql中,有一个创建之初自带的库information_schema
,这个库中包含着数据库相关信息,查询数据占用空间就是使用该库,所以首先进入这个库
-- 首先进入mysql系统库
use information_schema;
第二步:查询
1)查看MySQL服务器下所有数据库
1)查看MySQL服务器下所有数据库
SHOW DATABASES;
输出如下
mysql> SHOW DATABASES;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| performance_schema |
| sys |
| zabbix |
+--------------------+
5 rows in set (0.00 sec)
2.查看所有数据库容量大小
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
group by table_schema
order by sum(data_length) desc, sum(index_length) desc;
使用 sum(DATA_LENGTH/1024/1024)
统计占用MB大小,分为两块,一个是DATA_LENGTH
—数据 、INDEX_LENGTH
—索引。
-- 查询数据库中所有数据占用空间
SELECT
concat( round( sum( DATA_LENGTH / 1024 / 1024 ), 2 ), 'MB' ) AS DATA
FROM
TABLES;
输出如下
mysql> SELECT
-> concat( round( sum( DATA_LENGTH / 1024 / 1024 ), 2 ), 'MB' ) AS DATA
-> FROM
-> TABLES;
+-----------+
| DATA |
+-----------+
| 2881.08MB |
+-----------+
1 row in set (0.00 sec)
-- 查询指定 数据库 的 指定表 数据占用空间
SELECT
concat( round( sum( data_length / 1024 / 1024 ), 2 ), 'MB' ) AS DATA
FROM
TABLES
WHERE
table_schema = '{your database}'
AND table_name = '{your table name}';
-- 查询指定 数据库 的 指定表 索引占用空间
SELECT
concat( round( sum( index_length / 1024 / 1024 ), 2 ), 'MB' ) AS DATA
FROM
TABLES
WHERE
table_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='{zabbix}';
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;