Mysql

关注公众号 jb51net

关闭
首页 > 数据库 > Mysql > MySQL 空间使用大小查询

MySQL 数据库空间使用大小查询的方法实现

作者:csdn_aspnet

本文主要介绍了MySQL 数据库空间使用大小查询的方法实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

以下是 MySQL 数据库空间大小查询与管理的常用方法,基于最新实践整理:

一、查询数据库空间大小

1. 查看所有数据库空间

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_length+index_length)/1024/1024,2)) AS '总大小(MB)'
FROM information_schema.tables
GROUP BY table_schema
ORDER BY SUM(data_length) DESC;

此语句统计所有数据库的总数据量、索引量及碎片空间,结果按数据容量降序排列。

使用

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_length+index_length)/1024/1024,2)) AS '总大小(MB)'
FROM information_schema.tables
WHERE table_schema='sftzhzx_jy-241220'
GROUP BY table_schema
ORDER BY SUM(data_length) DESC;

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_length+index_length)/1024/1024,2)) AS '总大小(MB)'
FROM information_schema.tables
WHERE table_schema='sftzhzx_jd'
GROUP BY table_schema
ORDER BY SUM(data_length) DESC;

2. 查看指定数据库空间

SELECT
  table_schema AS '数据库',
  SUM(data_length + index_length)/1024/1024 AS '总大小(MB)'
FROM information_schema.tables
WHERE table_schema = 'your_database_name'
GROUP BY table_schema;

替换 your_database_name 后,可获取特定数据库的总空间占用。

使用

SELECT
  table_schema AS '数据库',
  SUM(data_length + index_length)/1024/1024 AS '总大小(MB)'
FROM information_schema.tables
WHERE table_schema = 'sftzhzx_jy-241220'
GROUP BY table_schema;

SELECT
  table_schema AS '数据库',
  SUM(data_length + index_length)/1024/1024 AS '总大小(MB)'
FROM information_schema.tables
WHERE table_schema = 'sftzhzx_jd'
GROUP BY table_schema;

二、查询表级空间占用

1. 查看数据库中所有表空间

SELECT
  table_name AS '表名',
  TRUNCATE(data_length/1024/1024,2) AS '数据容量(MB)',
  TRUNCATE(index_length/1024/1024,2) AS '索引容量(MB)',
  TRUNCATE((data_length+index_length)/1024/1024,2) AS '总大小(MB)'
FROM information_schema.tables
WHERE table_schema = 'your_database_name'
ORDER BY (data_length + index_length) DESC;

用于分析指定数据库内各表的空间分布,识别大表。

2. 精确查询单表空间

SELECT
  table_name AS '表名',
  TRUNCATE((data_length + index_length)/1024/1024,2) AS '总大小(MB)'
FROM information_schema.tables
WHERE table_schema = 'your_database_name'
  AND table_name = 'your_table_name';

适用于定位具体表的空间占用情况。

三、空间管理建议

1、自动扩展配置

在 my.cnf 配置文件中设置自动扩展参数,避免空间不足:

[mysqld]
innodb_data_file_path = ibdata1:10M:autoextend

2、独立表空间优化

启用独立表空间可提升管理灵活性:

SET GLOBAL innodb_file_per_table = 1;

3、定期清理碎片

对频繁更新的表执行优化命令:

OPTIMIZE TABLE your_table_name;

以上方法结合系统表查询与配置优化,可有效管理和监控数据库空间。

到此这篇关于MySQL 数据库空间使用大小查询的方法实现的文章就介绍到这了,更多相关MySQL 空间使用大小查询内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文