操做前先關閉數據庫緩存sql
#建立測試的test表數據庫
DROP TABLE IF EXISTS test; CREATE TABLE test( `id` INT(10) NOT NULL, `name` VARCHAR(20) DEFAULT '' NOT NULL, `status` TINYINT(1) DEFAULT 1 NOT NULL, PRIMARY KEY( ID ) )ENGINE=INNODB DEFAULT CHARSET utf8;
插入數據緩存
create procedure a() BEGIN DECLARE i INT DEFAULT 0; SET autocommit = 0; WHILE i<10000000 DO INSERT INTO test ( `id`,`name`,`status` ) VALUES( i, CONCAT( 'abcd', i ),i%3 ); SET i = i+1; IF i%2000 = 0 THEN // 每滿2000行執行一次 COMMIT; END IF; END WHILE; END; call a();
耗時: 0.042s
先測試帶主鍵模式下查詢主鍵執行時間測試
讀取10條數據 # in SELECT * FROM test WHERE id IN (1,2,3,4,5,6,7,8,9,10); 用時:0.001 # or SELECT * FROM test WHERE id =1 OR id=2 OR id=3 OR id=4 OR id=5 OR id=6 OR id=7 OR id=8 OR id=9 OR id=10; 用時:0.001 # between SELECT * FROM test WHERE id between 1 and 10; 用時:0.001 # <> SELECT * FROM test WHERE id>=1 and id<=10; 用時:0.001 # <= SELECT * FROM test WHERE id <= 10; 用時:0.001
讀取1000條數據 # in SELECT * FROM test WHERE id IN (1,2,3,...1000); 用時:0.003 # or SELECT * FROM test WHERE id =1 OR id=2 OR id=3 OR... id=1000; 用時:0.019 # between SELECT * FROM test WHERE id between 1 and 100; 用時:0.002 # <> SELECT * FROM test WHERE id>=1 and id<=1000; 用時:0.002 # <= SELECT * FROM test WHERE id <= 1000; 用時:0.002
讀取10000條數據 # in SELECT * FROM test WHERE id IN (1,2,3,...10000);
用時:0.027
# or
SELECT * FROM test WHERE id =1 OR id=2 OR id=3 OR... id=10000;
執行用時:4.834 # between SELECT * FROM test WHERE id between 1 and 10000; 用時:0.008 # <> SELECT * FROM test WHERE id>=1 and id<=10000; 用時:0.008 # <= SELECT * FROM test WHERE id <= 10000; 用時:0.008
讀取50000條數據(sql語句太長,10萬數據 in和or會崩潰) # in SELECT * FROM test WHERE id IN (1,2,3,...50000); 用時:5.193s # or SELECT * FROM test WHERE id =1 OR id=2 OR id=3 OR... id=50000; 用時:(sql語句太長,電腦崩潰) # between SELECT * FROM test WHERE id between 1 and 50000; 用時:0.035s # <> SELECT * FROM test WHERE id>=1 and id<=50000; 用時:0.032s # <= SELECT * FROM test WHERE id <= 50000; 用時:0.031s
在主鍵id上 in的效率要高於or;其它幾個比較符相近。spa
測試非主鍵 statuscode
讀取10000000條數據(一千萬條數據) # in SELECT * FROM test WHERE status IN (0,1); 用時:6.736s # or SELECT * FROM test WHERE status =0 OR status=1; 用時:6.655s # between SELECT * FROM test WHERE status between 0 and 1; 用時:6.476s # <> SELECT * FROM test WHERE status>=0 and status<=1; 用時:6.680s # <= SELECT * FROM test WHERE status <= 1; 用時:6.440s
# <> SELECT * FROM test WHERE status <> 2; 用時:6.263s
當id的主鍵索引去除後blog
讀取10000000條數據(一千萬條數據) # in SELECT * FROM test WHERE status IN (0,1); 用時:7.888s # or SELECT * FROM test WHERE status =0 OR status=1; 用時:7.770s # between SELECT * FROM test WHERE status between 0 and 1; 用時:7.989s # <= => SELECT * FROM test WHERE status>=0 and status<=1; 用時:7.835s # <= SELECT * FROM test WHERE status <= 1; 用時:7.476s # <> SELECT * FROM test WHERE status <> 2; 用時:8.346s
非主鍵字段有無主鍵索引差距不是很大。索引
強制走主鍵索引it
select * from test force index(PRIMARY) where status in (0,1);用時:10.930