一切源於一個實驗,請看下面的例子:
表:
CREATE TABLE IF NOT EXISTS `foo` ( `a` int(10) unsigned NOT NULL AUTO_INCREMENT, `b` int(10) unsigned NOT NULL, `c` varchar(100) NOT NULL, PRIMARY KEY (`a`), KEY `bar` (`b`,`a`) ) ENGINE=InnoDB; CREATE TABLE IF NOT EXISTS `foo2` ( `a` int(10) unsigned NOT NULL AUTO_INCREMENT, `b` int(10) unsigned NOT NULL, `c` varchar(100) NOT NULL, PRIMARY KEY (`a`), KEY `bar` (`b`,`a`) ) ENGINE=MyISAM;
我往兩個表中插入了30w的數據(插入的時候性能差別InnoDB比MyISAM慢)
<?php $host = '192.168.100.166'; $dbName = 'test'; $user = 'root'; $password = ''; $db = mysql_connect($host, $user, $password) or die('DB connect failed'); mysql_select_db($dbName, $db); echo '===================InnoDB=======================' . "\r\n"; $start = microtime(true); mysql_query("SELECT SQL_NO_CACHE SQL_CALC_FOUND_ROWS * FROM foo WHERE b = 1 LIMIT 1000, 10"); $end = microtime(true); echo $end - $start . "\r\n"; echo '===================MyISAM=======================' . "\r\n"; $start = microtime(true); mysql_query("SELECT SQL_NO_CACHE SQL_CALC_FOUND_ROWS * FROM foo2 WHERE b = 1 LIMIT 1000, 10"); $end = microtime(true); echo $end - $start . "\r\n";
返回結果:
一次查詢就會差別這么多!!InnoDB和MyISAM,趕緊分析分析為什么。
首先是使用explain來進行查看
確定兩邊都沒有使用index,第二個查詢查的rows,並且MyISAM的查詢rows還比InnoDB少這么多,反而是查詢慢於InnoDB!!這Y的有點奇怪。
沒事,還有一個牛掰工具profile
具體使用可以參考:http://dev.mysql.com/doc/refman/5.0/en/show-profile.html
使用方法簡單來說:
Mysql > set profiling = 1; Mysql>show profiles; Mysql>show profile for query 1;
這個數據中就可以看到MyISAM的Sending data比InnoDB的Sending data費時太多了。查看mysql文檔
http://dev.mysql.com/doc/refman/5.0/en/general-thread-states.html
Sending data
The thread is reading and processing rows for a SELECT statement, and sending data to the client. Because operations occurring during this this state tend to perform large amounts of disk access (reads), it is often the longest-running state over the lifetime of a given query.
Sending data是去磁盤中讀取select的結果,然后將結果返回給客戶端。這個過程會有大量的IO操作。你可以使用show profile cpu for query XX;來進行查看,發現MyISAM的CPU_system比InnnoDB大很多。至此可以得出結論是MyISAM進行表查詢(區別僅僅使用索引就可以完成的查詢)比InnoDB慢。
至於再往下的為什么,我想就需要看源碼了..於是,就此打住。
附帶一篇文章,里面還有status的用法
http://hi.baidu.com/thinkinginlamp/item/8d038333c6b0674a3075a1d3
參考文章:
http://dev.mysql.com/doc/refman/5.0/en/show-profile.html
http://stackoverflow.com/questions/6274891/mysql-innodb-count-vs-counting-rows-on-server-side
http://www.yqshare.com/mysql-sql-show-profile.html
http://stackoverflow.com/questions/3638624/mysql-profiler-sending-data
http://hi.baidu.com/hexie007/item/126939785b86353c714423cd
http://moonbingbing.blogspot.com/2010/12/mysql-profilesending-data.html