零、背景
這周四收到很多告警,找DBA看了看,發現有個慢查詢。
簡單收集一些信息后,發現這個慢查詢問題隱藏的很深,問了好多人包括DBA都不知道原因。
一、問題
有一個DB, 有一個字段, 定義如下.
| MySQL [d_union_stat]> desc t_local_cache_log_meta;+----------------+--------------+------+-----+---------------------+| Field | Type | Null | Key | Default |+----------------+--------------+------+-----+---------------------+| c_id | int(11) | NO | PRI | NULL || c_key | varchar(128) | NO | MUL | || c_time | int(11) | NO | MUL | 0 || c_mtime | varchar(45) | NO | MUL | 0000-00-00 00:00:00 |+----------------+--------------+------+-----+---------------------+17 rows in set (0.01 sec) |
索引如下:
| MySQL [d_union_stat]> show index from t_local_cache_log_meta /G *************************** 1. row *************************** Table: t_local_cache_log_meta Non_unique: 0 Key_name: PRIMARY Column_name: c_id Collation: A Cardinality: 6517096 Index_type: BTREE*************************** 2. row ***************************...*************************** 6. row *************************** Table: t_local_cache_log_meta Non_unique: 1 Key_name: index_mtime Column_name: c_mtime Collation: A Cardinality: 592463 Index_type: BTREE6 rows in set (0.02 sec) |
然后我寫了一個SQL如下:
| SELECT count(*)FROM d_union_stat.t_local_cache_log_metawhere `c_mtime` < FROM_UNIXTIME(1494485402); |
終于有一天DBA過來了, 扔給我一個流水,說這個SQL是慢SQL。
| # Time: 170518 11:31:14# Query_time: 12.312329 Lock_time: 0.000061 Rows_sent: 0 Rows_examined: 5809647SET timestamp=1495078274;DELETE FROM `t_local_cache_log_meta` WHERE `c_mtime`< FROM_UNIXTIME(1494473461) limit 1000; |
我頓時無語了,我的DB都是加了索引,SQL都是精心優化了的,怎么是慢SQL呢?
問為什么是慢SQL,DBA答不上來, 問了周圍的同事也都答不上來。
我心里暗想遇到一個隱藏很深的知識點了。
令人懷疑的地方有兩個:1.有6個索引。 2. 右值是 FROM_UNIXTIME 函數。
于是查詢MYSQL官方文檔,發現6個不是問題。
All storage engines support at least 16 indexes per table and a total index length of at least 256 bytes.
Most storage engines have higher limits.
于是懷疑問題是 FROM_UNIXTIME 函數了。
然后看看MYSQL的INDEX小節,找到一點蛛絲馬跡。
1.To find the rows matching a WHERE clause quickly.
2. To eliminate rows from consideration.
If there is a choice between multiple indexes, MySQL normally uses the index that finds the smallest number of rows.
新聞熱點
疑難解答