Cú pháp truy vấn
Lọc bảng có table_rows >= 1 trong information_schema.tables:
SELECT table_type, table_name, table_schema FROM information_schema.tables WHERE table_rows >= 1 AND table_schema = 'ten_database';
Ví dụ với database "test"
mysql> SELECT table_type, table_name, table_schema -> FROM information_schema.tables -> WHERE table_rows >= 1 AND table_schema = 'test';
Kết quả (rút gọn)
+------------+------------------------------+--------------+ | TABLE_TYPE | TABLE_NAME | TABLE_SCHEMA | +------------+------------------------------+--------------+ | BASE TABLE | add30minutesdemo | test | | BASE TABLE | addoneday | test | | BASE TABLE | agecalculatesdemo | test | | BASE TABLE | aliasdemo | test | | ... | ... | ... | | BASE TABLE | zipcodepadwithzerodemo | test | +------------+------------------------------+--------------+ 80 rows in set (0.00 sec)
Lưu ý quan trọng
⚠️ table_rows là ước lượng!
- InnoDB: Có thể báo 0 dù bảng có dữ liệu (chưa cập nhật thống kê)
- Chạy
ANALYZE TABLE ten_bang;để cập nhật thống kê - Để chính xác 100%: Cần
COUNT(*)thực tế
Phiên bản chính xác (chậm hơn)
SELECT t.table_name,
(SELECT COUNT(*) FROM `ten_database`.`t`.`table_name`) AS exact_count
FROM information_schema.tables t
WHERE t.table_schema = 'ten_database'
HAVING exact_count > 0;
Ứng dụng thực tế
- Dọn dẹp database: Xác định bảng rỗng để xóa
- Migration: Chỉ migrate bảng có dữ liệu
- Backup: Ưu tiên backup bảng có dữ liệu
- Phân tích: Hiểu phân bố dữ liệu
Kết hợp với kích thước bảng
SELECT
table_name,
table_rows AS estimated_rows,
ROUND((data_length + index_length) / 1024 / 1024, 2) AS size_mb
FROM information_schema.tables
WHERE table_schema = 'ten_database' AND table_rows >= 1
ORDER BY size_mb DESC;