現在我們有一個8500萬條多個字段組成的股票數據表,以下是用count(*)語法查看總條目
mysql> select count(*) from stock_num; +----------+ | count(*) | +----------+ | 85429756 | +----------+ 1 row in set (1 min 3.61 sec)
1分鍾剛過。
表中有一個字段type 類型爲char(2) 聲明股票類型的, 這個字段沒有索引,測試一下count這個字段, 結果等了4分多鍾沒有反應, kill掉了。
mysql> select count(type) from stock_num; ^CCtrl-C -- sending "KILL QUERY 172163" to server ... Ctrl-C -- query aborted. ERROR 1317 (70100): Query execution was interrupted
還有一個字段num 類型爲int(10) 記錄股票關聯數據量的, 這個字段也沒有索引, count一下, 結果也是一樣, 等太久, 被迫kill掉了
mysql> select count(num) from stock_num; ^CCtrl-C -- sending "KILL QUERY 172163" to server ... Ctrl-C -- query aborted. ERROR 1317 (70100): Query execution was interrupted
現在測試stockCode這個字段, 類型爲char(6) 記錄股票代碼的, 這個字段有索引, 結果如下, 所用時間和count(*)差不多, 也是1分鍾多一點。
mysql> select count(stockCode) from stock_num; +------------------+ | count(stockCode) | +------------------+ | 85430691 | +------------------+ 1 row in set (1 min 2.34 sec)
表中的主鍵爲id, 類型爲char(32), 存的哈希值, 結果如下:
mysql> select count(id) from stock_num; +-----------+ | count(id) | +-----------+ | 85430965 | +-----------+ 1 row in set (57.83 sec)
用了將近1分鍾, 結論:在mysql5.6的環境下, count(主鍵)的方法是效率最快的。