問題描述
當SELECT語句中使用SLEEP時,何時觸發SLEEP操作?
模擬測試
mysql> show create table tb1001 \G
*************************** 1. row ***************************
Table: tb1001
Create Table: CREATE TABLE `tb1001` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`c1` int(11) NOT NULL,
`c2` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `UNI_C1` (`c1`)
) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8
1 row in set (0.01 sec)
mysql> select sleep(1),id,c1 from tb1001 where c2<2 limit 3;
+----------+----+----+
| sleep(1) | id | c1 |
+----------+----+----+
| 0 | 1 | 1 |
+----------+----+----+
1 row in set (1.01 sec)
mysql> select sleep(1),id,c1 from tb1001 where c2<1;
Empty set (0.00 sec)
mysql> select sleep(1),id,c1 from tb1001 where c2<2;
+----------+----+----+
| sleep(1) | id | c1 |
+----------+----+----+
| 0 | 1 | 1 |
+----------+----+----+
1 row in set (1.00 sec)
mysql> select sleep(1),id,c1 from tb1001 where c2<3;
+----------+----+----+
| sleep(1) | id | c1 |
+----------+----+----+
| 0 | 1 | 1 |
| 0 | 2 | 2 |
+----------+----+----+
2 rows in set (2.00 sec)
mysql> select sleep(1),id,c1 from tb1001 where c2<4;
+----------+----+----+
| sleep(1) | id | c1 |
+----------+----+----+
| 0 | 1 | 1 |
| 0 | 2 | 2 |
| 0 | 3 | 3 |
+----------+----+----+
3 rows in set (3.00 sec)
測試分析
從上面的測試結果看,由於C2上沒有索引,需要全表掃描,查詢執行時間和查詢返回的數據行記錄成正比,與查詢掃描的記錄行數無關。
在<深入理解MySQL主從原理>書中描述:
- 每當InnoDB層返回一行數據經過WHERE條件判斷后,都會觸發Sleep函數,也就是經過WHERE條件過濾的數據,在發送給客戶端前都會進行異常SLEEP操作。
擴展知識
可以通過LIMIT來限制發送給客戶端的操作,因此可以通過SLEEP+LIMIT操作來控制語句執行時間,方便模擬執行時間較長的SQL。
mysql> select sleep(1),id from tb1001 limit 1;
+----------+----+
| sleep(1) | id |
+----------+----+
| 0 | 1 |
+----------+----+
1 row in set (1.01 sec)
mysql> select sleep(1),id from tb1001 limit 2;
+----------+----+
| sleep(1) | id |
+----------+----+
| 0 | 1 |
| 0 | 2 |
+----------+----+
2 rows in set (2.00 sec)