跳到主要内容

mysql常用命令集合

Here is 简介!

mysql 常用命令集合

查看库表大小

1、所有数据库的大小

通过统计每个数据库下所有表的「数据大小 + 索引大小」之和,得到数据库总大小(单位默认是字节,需转换为 MB/GB 更易读)。

SELECT
table_schema AS '数据库名', -- 数据大小(字节)
SUM(data_length) AS '数据总大小(字节)', -- 索引大小(字节)
SUM(index_length) AS '索引总大小(字节)', -- 总大小(数据+索引,转换为 MB)
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS '总大小(MB)', -- 总大小(转换为 GB,保留2位小数)
ROUND(SUM(data_length + index_length) / 1024 / 1024 / 1024, 2) AS '总大小(GB)'
FROM
information_schema.tables
GROUP BY
table_schema
ORDER BY
SUM(data_length + index_length) DESC;
  • table_schema:数据库名称;
  • data_length:表数据占用的字节数;
  • index_length:表索引占用的字节数;

2、指定数据库的大小

查看名为  test_db  的数据库大小:

SELECT
table_schema AS '数据库名',
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS '总大小(MB)',
ROUND(SUM(data_length + index_length) / 1024 / 1024 / 1024, 2) AS '总大小(GB)'
FROM
information_schema.tables
WHERE
table_schema = 'test_db' -- 替换为目标数据库名
GROUP BY table_schema;

3、指定数据库中所有表的大小

查看  test_db  数据库中所有表的大小(按总大小倒序):

SELECT
table_name AS '表名', -- 数据大小(MB)
ROUND(data_length / 1024 / 1024, 2) AS '数据大小(MB)', -- 索引大小(MB)
ROUND(index_length / 1024 / 1024, 2) AS '索引大小(MB)', -- 总大小(MB)
ROUND((data_length + index_length) / 1024 / 1024, 2) AS '总大小(MB)'
FROM
information_schema.tables
WHERE
table_schema = 'dtdh' -- 替换为目标数据库名
ORDER BY
(data_length + index_length) DESC;

4、单个表大小

查看  test_db  数据库中  user  表的大小:

SELECT
table_name AS '表名',
ROUND(data_length / 1024 / 1024, 2) AS '数据大小(MB)',
ROUND(index_length / 1024 / 1024, 2) AS '索引大小(MB)',
ROUND((data_length + index_length) / 1024 / 1024, 2) AS '总大小(MB)'
FROM
information_schema.tables
WHERE
table_schema = 'dtdh' -- 数据库名
AND table_name = 'event_chain'; -- 表名