2017年12月17日 星期日

MySQL 時間函數 NOW() 和 SYSDATE() 的差異

NOW():返回該句 SQL(或stored function、trigger ) 開始執行的時間。
SYSDATE() :返回執時到此函式的時間。

所以,
一句 SQL 有多個 NOW(),返回值一定相同;
一句 SQL 有多個 SYSDATE(),返回值不一定相同,會受執行花費時間影響。


NOW()不管在何處,返回時間都一樣。
mysql> SELECT NOW(), SLEEP(2), NOW();
+---------------------+----------+---------------------+
| NOW()               | SLEEP(2) | NOW()               |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:36 |        0 | 2006-04-12 13:47:36 |
+---------------------+----------+---------------------+



SYSDATE() 返回執行到該函式的時間,所不一定相同。
mysql> SELECT SYSDATE(), SLEEP(2), SYSDATE();
+---------------------+----------+---------------------+
| SYSDATE()           | SLEEP(2) | SYSDATE()           |
+---------------------+----------+---------------------+
| 2006-04-12 13:47:44 |        0 | 2006-04-12 13:47:46 |
+---------------------+----------+---------------------+



參考:MySQL :: MySQL 5.7 Reference Manual :: 12.7 Date and Time Functions
「NOW() returns a constant time that indicates the time at which the statement began to execute.
(Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.
This differs from the behavior for SYSDATE(), which returns the exact time at which it executes.」


沒有留言:

張貼留言