萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> MySQL 教學

MySQL 查看數據庫/表大小 SQL 命令速查

核心思路

查詢 information_schema.TABLES 視圖,聚合 data_length(數據大小)+ index_length(索引大小)即得表總大小,單位轉換為 MB/GB。

常用查詢

-- 1. 進入信息庫
USE information_schema;

-- 2. 所有數據庫總大小(MB)
SELECT CONCAT(ROUND(SUM(data_length + index_length) / 1024 / 1024, 2), ' MB') AS total_size
FROM tables;

-- 3. 指定數據庫大小(如 db_name)
SELECT CONCAT(ROUND(SUM(data_length + index_length) / 1024 / 1024, 2), ' MB') AS db_size
FROM tables
WHERE table_schema = 'db_name';

-- 4. 指定數據庫下各表大小(含行數、引擎)
SELECT table_name,
       CONCAT(ROUND((data_length + index_length) / 1024 / 1024, 2), ' MB') AS total_size,
       table_rows,
       engine
FROM tables
WHERE table_schema = 'db_name'
ORDER BY (data_length + index_length) DESC;

-- 5. 單表大小(如 db_name.tbl_name)
SELECT CONCAT(ROUND((data_length + index_length) / 1024 / 1024, 2), ' MB') AS tbl_size
FROM tables
WHERE table_schema = 'db_name' AND table_name = 'tbl_name';

進階:按 Schema 彙總 Top 10 大庫

SELECT table_schema AS `Database`,
       CONCAT(ROUND(SUM(data_length + index_length) / 1024 / 1024, 2), ' MB') AS `Size`
FROM tables
GROUP BY table_schema
ORDER BY SUM(data_length + index_length) DESC
LIMIT 10;

注意

  • data_length 不含碎片空間(data_free),實際磁盤佔用 = data_length + index_length + data_free。
  • InnoDB 共享表空間模式下 (innodb_file_per_table=OFF) 系統表空間 ibdata1 大小不在此統計範圍,需文件系統級查看。
copyright © 萬盛學電腦網 all rights reserved