关于MySQL的SLEEP(N)函数

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

[sql]  view plain  copy
 
  1. mysql> select sleep(1);  
  2. +----------+  
  3. | sleep(1) |  
  4. +----------+  
  5. |        0 |  
  6. +----------+  
  7. 1 row in set (1.00 sec)  

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

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

[sql]  view plain  copy
 
  1. mysql> select name from animals where name='tiger';  
  2. +-------+  
  3. name  |  
  4. +-------+  
  5. | tiger |  
  6. +-------+  
  7. 1 row in set (0.00 sec)  

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

[sql]  view plain  copy
 
  1. mysql> select sleep(1),name from animals where name='tiger';  
  2. +----------+-------+  
  3. | sleep(1) | name  |  
  4. +----------+-------+  
  5. |        0 | tiger |  
  6. +----------+-------+  
  7. 1 row in set (1.00 sec)  

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

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

[sql]  view plain  copy
 
  1. mysql> select name from animals where name='pig';  
  2. Empty set (0.00 sec)  

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

[sql]  view plain  copy
 
  1. mysql> select sleep(1),name from animals where name='pig';  
  2. Empty set (0.00 sec)  

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

[sql]  view plain  copy
 
  1. mysql> select name from animals where name like '%ger';  
  2. +-------+  
  3. name  |  
  4. +-------+  
  5. | ger   |  
  6. | iger  |  
  7. | tiger |  
  8. +-------+  
  9. rows in set (0.00 sec)  

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

[sql]  view plain  copy
 
  1. mysql> select sleep(1),name from animals where name like '%ger';  
  2. +----------+-------+  
  3. | sleep(1) | name  |  
  4. +----------+-------+  
  5. |        0 | ger   |  
  6. |        0 | iger  |  
  7. |        0 | tiger |  
  8. +----------+-------+  
  9. rows in set (3.01 sec)  

转载地址:https://blog.csdn.net/zyz511919766/article/details/42241211

原文地址:https://www.cnblogs.com/chinasoft/p/14794111.html