最近出現一個很奇怪的MySQL問題,使用不同select語句查詢全部資料集居然得到不同的記錄數。select * 得到4條記錄,select 欄位得到的是3條記錄。
具體問題可以看下面的查詢結果:
[sql]
mysql> select * from table_myisam;
+----------+-------+-----------+------+
| datetime | uid | content | type |
+----------+-------+-----------+------+
|1 | uid_1 | content_1 |1 |
|2 | uid_2 | content_2 |1 |
|4 | uid_4 | content_4 |1 |
|3 | uid_3 | content_3 |1 |
+----------+-------+-----------+------+
4 rows in set (0.00 sec)
mysql> select uid from table_myisam;
+-------+
| uid |
+-------+
| uid_1 |
| uid_2 |
| uid_4 |
+-------+
3 rows in set (0.00 sec)
通過select uid只得到3行記錄,丟失了其中uid='uid_3'的記錄。本來百思不得其解,後來在同事的提醒下使用了check table,才找到問題的所在。
[sql]
mysql> check table table_myisam;
+--------------------+-------+----------+-------------------------------------------------------+
| Table | Op| Msg_type | Msg_text |
+--------------------+-------+----------+-------------------------------------------------------+
| qitai.table_myisam | check | warning | 1 client is using or hasn't closed the table properly |
| qitai.table_myisam | check | warning | Size of indexfile is: 2049 Should be: 2048 |
| qitai.table_myisam | check | error| Found 3 keys of 4 |
| qitai.table_myisam | check | error| Corrupt |
+--------------------+-------+----------+-------------------------------------------------------+
查詢資料不一致的原因是table_myisam的索引檔案損壞了,對應的索引檔案table_myisam.MYI與資料檔案table_myisam.MYD不一致。select *並不需要遍曆每個索引項目,只需要擷取第一條記錄,根據鏈表順序訪問,因此當前的索引損壞並沒有影響到select *的使用。而select uid需要遍曆所有索引項目,因而只擷取到損壞狀態,三條索引記錄。
解決方案是使用repair table進行表索引的修複。
[sql]
mysql> repair table table_myisam;
+--------------------+--------+----------+----------+
| Table | Op | Msg_type | Msg_text |
+--------------------+--------+----------+----------+
| qitai.table_myisam | repair | status | OK |
+--------------------+--------+----------+----------+
1 row in set (0.00 sec)
修複後使用check table可以看到表狀態變成正常,使用select *與select uid都能擷取到4條記錄。
[sql]
mysql> check table table_myisam;
+--------------------+-------+----------+----------+
| Table | Op| Msg_type | Msg_text |
+--------------------+-------+----------+----------+
| qitai.table_myisam | check | status | OK |
+--------------------+-------+----------+----------+
1 row in set (0.00 sec)