【浅析mysql的设计】浅析MySQL的SLEEP(N)函数作用及应用场景

时间:2019-09-03  来源:php函数  阅读:

都知道通过在MySQL中执行select sleep(N)可以让此语句运行N秒钟:

mysql> select sleep(1);
+----------+
| sleep(1) |
+----------+
|        0 |
+----------+
1 row in set (1.00 sec)

返回给客户端的执行时间显示出等待了1秒钟

借助于sleep(N)这个函数我们可以在MySQL Server的PROCESSLIST中捕获到执行迅速不易被查看到的语句以确定我们的程序是否确实在Server端发起了该语句。比如我们在调试时想确定一下程序是否确确实实向Server发起了执行SQL语句的请求,那么我们可以通过执行show processlist或者由information_schema.processlist表来查看语句是否出现。但往往语句执行速度可能非常快,这样的话就很难通过上述办法确定语句是否真正被执行了。例如下面语句的执行时间为0.00秒,线程信息一闪而过,根本无从察觉。

mysql> select name from animals where name="tiger";
+-------+
| name  |
+-------+
| tiger |
+-------+
1 row in set (0.00 sec)

在这种情况下,可以通过在语句中添加一个sleep(N)函数,强制让语句停留N秒钟,来查看后台线程,例如:

mysql> select sleep(1),name from animals where name="tiger";
+----------+-------+
| sleep(1) | name  |
+----------+-------+
|        0 | tiger |
+----------+-------+
1 row in set (1.00 sec)

同样的条件该语句返回的执行时间为1.0秒。

但是使用这个办法是有前提条件的,也只指定条件的记录存在时才会停止指定的秒数,例如查询条件为name="pig",结果表明记录不存在,执行时间为0

mysql> select name from animals where name="pig";
Empty set (0.00 sec)

在这样一种条件下,即使添加了sleep(N)这个函数,语句的执行还是会一闪而过,例如:

mysql> select sleep(1),name from animals where name="pig";
Empty set (0.00 sec)

另外需要注意的是,添加sleep(N)这个函数后,语句的执行具体会停留多长时间取决于满足条件的记录数,MySQL会对每条满足条件的记录停留N秒钟。
例如,name like "%ger"的记录有三条

mysql> select name from animals where name like "%ger";
+-------+
| name  |
+-------+
| ger   |
| iger  |
| tiger |
+-------+
3 rows in set (0.00 sec)

那么针对该语句添加了sleep(1)这个函数后语句总的执行时间为3.01秒,可得出,MySQL对每条满足条件的记录停留了1秒中。

mysql> select sleep(1),name from animals where name like "%ger";
+----------+-------+
| sleep(1) | name  |
+----------+-------+
|        0 | ger   |
|        0 | iger  |
|        0 | tiger |
+----------+-------+
3 rows in set (3.01 sec)

 

总结:这个函数我目前主要是用在调试sql语句上,在应用项目止暂时还未用过。

【浅析mysql的设计】浅析MySQL的SLEEP(N)函数作用及应用场景

http://m.bbyears.com/jiaocheng/65884.html

推荐访问:
相关阅读 猜你喜欢
本类排行 本类最新