mysql獲取當前時間,前一天,後一天

2021-08-02 20:44:50 字數 1612 閱讀 1076

負責的專案中,使用的是mysql資料庫,頁面上要顯示當天所註冊人數的數量,獲取當前的年月日,我使用的是 curdate(),

錯誤的sql語句

eg:select count(*) from user where registerdate >= curdate() and registerdate < curdate()+1;

雖然 獲取到的數量在測試環境中是正確的,但在發布到線上的時候,發現有的時候資料是查詢不到,數量為0,因此,就上網查詢是不是curdate()+1不規範,發現mysql官網也是不承認時間直接相加減的,雖然會將當前時間轉換為20160802,這時候就是比較這一串字元,mysql官網是不承認用這種方式比較時間大小的,因此:

正確的sql語句

eg:select count(*) from user where registerdate >= curdate() and registerdate < date_sub(curdate(),interval -1 day);

此時,就用到了date_sub()這個函式,用法舉例:

今天是2023年08月01日。

date_sub('2016-08-01',interval 1 day) 表示 2016-07-31

date_sub('2016-08-01',interval 0 day) 表示 2016-08-01

date_sub('2016-08-01',interval -1 day) 表示 2016-08-02

date_sub(curdate(),interval 1 day) 表示 2016-07-31

date_sub(curdate(),interval -1 day) 2016-08-02

date_sub(curdate(),interval 1 month) 表示 2016-07-01

date_sub(curdate(),interval -1 month) 表示 2016-09-01

date_sub(curdate(),interval 1 year) 表示 2015-08-01

date_sub(curdate(),interval -1 year) 表示 2017-08-01

假設我們有如下的表:

orderid

productname

orderdate

1'computer'

2008-12-29 16:25:46.635

現在,我們希望向 "orderdate" 新增 2 天,這樣就可以找到付款日期。

我們使用下面的 select 語句:

select orderid,date_add(orderdate,interval 2 day)as orderpaydate

from orders

結果:

orderid

orderpaydate

12008-12-31 16:25:46.635

備註:select now(),curdate(),curtime()

結果類似:

now()

curdate()

curtime()

2016-08-01 16:25:46

2016-08-01

16:25:46

mysql獲取當前時間,前一天,後一天

原文 負責的專案中,使用的是mysql資料庫,頁面上要顯示當天所註冊人數的數量,獲取當前的年月日,我使用的是 curdate 錯誤的sql語句 eg select count from user where registerdate curdate and registerdate curdate ...

mysql獲取當前時間,前一天,後一天

負責的專案中,使用的是mysql資料庫,頁面上要顯示當天所註冊人數的數量,獲取當前的年月日,我使用的是 curdate 錯誤的sql語句 eg select count from user where registerdate curdate and registerdate curdate 1 雖...

mysql獲取當前時間,前一天,後一天

負責的專案中,使用的是mysql資料庫,頁面上要顯示當天所註冊人數的數量,獲取當前的年月日,我使用的是 curdate 錯誤的sql語句 eg select count from user where registerdate curdate and registerdate curdate 1 雖...