MySQL · 案例分析 · information_schema.tables 与 count(*) 查询数不一致

问题现象

查询表 mqm.t_batch 总行数,发现两种方式查询的结果不一致。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# information_schema.tables
mysql> select table_name,table_rows from information_schema.tables where TABLE_SCHEMA = 'mqm' and table_name='t_batch';
+------------+------------+
| table_name | table_rows |
+------------+------------+
| t_batch | 9527271 |
+------------+------------+
1 row in set (0.02 sec)

# count(*)
mysql> select count(*) from t_batch;
+----------+
| count(*) |
+----------+
| 10474287 |
+----------+
1 row in set (21.52 sec)

原因分析

默认情况下,MySQL 对表进行增删操作时,是不会自动更新 information_schema.tablestable_rows 字段,只有 10% 的行数发生变化才会自动收集,执行 ANALYZE TABLE 'table_name' 后会统计所有表数据,结果和 count(*) 一致。

Tips:生产环境中不建议使用,因为会锁表!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
mysql> ANALYZE TABLE t_batch;
+-------------+---------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+-------------+---------+----------+----------+
| mqm.t_batch | analyze | status | OK |
+-------------+---------+----------+----------+
1 row in set (3.85 sec)

mysql> select table_name,table_rows from information_schema.tables where TABLE_SCHEMA = 'mqm' and table_name='t_batch';
+------------+------------+
| table_name | table_rows |
+------------+------------+
| t_batch | 10261904 |
+------------+------------+
1 row in set (0.07 sec)