USE information_schema;
SELECT table_name, table_rows
FROM tables
WHERE table_schema = 'testdb'
ORDER BY table_rows DESC;
table_rows 為估算值(誤差可達 40~50%),非精確計數。USE information_schema;
SELECT CONCAT(
'SELECT "', TABLE_NAME, '", COUNT(*) FROM ',
TABLE_SCHEMA, '.', TABLE_NAME, ' UNION ALL'
)
FROM tables
WHERE TABLE_SCHEMA = 'testdb';
執行結果會產生一連串 UNION ALL 查詢,複製貼上執行即得精確行數。適合一次性稽核,不建議頻繁執行(全表掃描)。
USE information_schema;
SELECT
table_schema,
table_name,
table_rows,
engine,
ROUND(data_length/1024/1024, 2) AS data_mb,
ROUND(index_length/1024/1024, 2) AS index_mb,
ROUND((data_length+index_length)/1024/1024, 2) AS total_mb
FROM tables
WHERE table_schema = 'testdb'
ORDER BY table_rows DESC;
一次掌握:資料庫、表名、估算行數、儲存引擎、資料大小、索引大小、總大小(單位 MB)。
SELECT
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS total_mb
FROM information_schema.TABLES
WHERE table_schema = '資料庫名';
INSERT/DELETE 觸發器更新獨立統計表,查詢 O(1)。table_rows 準確度。| 需求 | 推薦方法 | 備註 |
|---|---|---|
| 快速估算、監控儀表板 | 方法一 | InnoDB 僅供參考 |
| 精確稽核、對帳 | 方法二或觸發器方案 | 接受全表掃描成本 |
| 容量規劃、備份評估 | 方法三 | 含大小、引擎完整資訊 |