查看 MySQL 各 Table 的使用空間

想知道 MySQL 每個 Table 到底使用多少空間, 如果是用 MyISAM 格式, 直接 ls -lh 去看即可. (下述路徑是 Debian Linux 預設 MySQL DB 存放路徑)

查看 MySQL Table 使用容量 (看 *.MYI)

  • ls -lh /var/lib/mysql/DB_NAME/
  • ls -lh /var/lib/mysql/DB_NAME/ | grep MYI # root 身份 可以直接 ls -lh /var/lib/mysql/DB_NAME/*.MYI

取出 MySQL Table 使用容量 依容量大小排序

  • ls -l /var/lib/mysql/DB_NAME/ | grep MYI | awk '{print $5,$8}' | sort -nr
  • 簡化: ls -l /var/lib/mysql/DB_NAME/ | awk '/MYI/ {print $5,$8}' | sort -nr # 感謝
    artchiu 提供

不過若使用 InnoDB, 因為檔案只有一個, 就沒辦法使用此方法來查.

要算各 Table 的容量, 可以下述步驟去算:

  1. mysql> SHOW TABLE STATUS;
  2. 將 Data_length * Index_length 即可.

此篇文章有寫程式去算各 Table 的容量: Getting MySQL table size with PHP

轉載上述文章的程式 (view_table_size.php):


<?php
$link = mysql_connect('host', 'username', 'password');

$db_name = "your database name here";
$tables = array();

mysql_select_db($db_name, $link);
$result = mysql_query("SHOW TABLE STATUS");

while($row = mysql_fetch_array($result)) {
    /* We return the size in Kilobytes */
    $total_size = ($row[ "Data_length" ] + $row[ "Index_length" ]) / 1024;
    $tables[$row['Name']] = sprintf("%.2f", $total_size);
}
 
print_r($tables);
?>

執行

  • php view_table_size.php # 即可看到結果

此程式看到的是 k bytes, 由此行做轉換: $row[ "Data_length" ] + $row[ "Index_length" ] / 1024, 若要換算成 Mb 就再除一次 1024 即可~ 🙂

作者: Tsung

對新奇的事物都很有興趣, 喜歡簡單的東西, 過簡單的生活.

在〈查看 MySQL 各 Table 的使用空間〉中有 4 則留言

  1. ls -l /var/lib/mysql/DB_NAME/ | grep MYI | awk '{print $5,$8}' | sort -nr
    可以精簡成
    ls -l /var/lib/mysql/DB_NAME/ | awk '/MYI/ {print $5,$8}' | sort -nr
    🙂

  2. 偶然發現這個 sql 也頗好用:
    SELECT concat(table_schema,'.',table_name),
    concat(round(table_rows/1000000,2),'M') rows,
    concat(round(data_length/(1024*1024*1024),2),'G') DATA,
    concat(round(index_length/(1024*1024*1024),2),'G') idx,
    concat(round((data_length+index_length)/(1024*1024*1024),2),'G') total_size,
    round(index_length/data_length,2) idxfrac
    FROM information_schema.TABLES
    ORDER BY data_length+index_length DESC LIMIT 20;

Tsung 發表迴響取消回覆

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料