MySql 操作時間

2021-09-22 05:48:23 字數 3456 閱讀 6363

這篇部落格的記錄,主要是在這次的專案中運用到了很多時間函式,才發現自己對mysql的時間函式記憶不夠,在統計中,很多地方都是用到時間進行統計,而靈活運用sql函式,可以事半功倍。

找出當前今天的資料:

select

*from

table

where

date

(時間字段)

= curdate(

);

date(),這個函式用於將時間格式(年月日 時分秒)轉換成年月日,curdate()函式是獲取當前的年月日,now()是獲取當前年月日 時分秒

找出前一天的資料:

select

*from

table

where date_sub(時間字段,

interval

1day

)select

*from

table

where

date

(時間字段)

= date_sub(curdate(),

interval

1day

)

date_sub()函式得到指定日期前一天的日期/把1改為任意數字就可以得到前n天的日期,還有乙個和它相反的函式

date_add()函式得到指定日期後一天的日期/把1改為任意數字就可以得到後n天的日期

其他用法

select

* date_sub(

'2019-05-10'

,interval

1day

) 表示 2019-05

-09select

* date_sub(

'2019-05-10'

,interval

0day

) 表示 2019-05

-10select

* date_sub(

'2019-05-10'

,interval-1

day) 表示 2019-05

-11select

* date_sub(curdate(),

interval

1month

) 表示 2019-04

-10select

* date_sub(curdate(),

interval-1

month

) 表示 2019-06

-10select

* date_sub(curdate(),

interval

1year

) 表示 2018-05

-10select

* date_sub(curdate(),

interval-1

year

) 表示 2019-05

-10

兩個時間中間差多少天:

select datediff(

'2019-05-10'

,'2019-05-09'

); 得到的結果為:1

datediff()函式用於時間相減

獲取上個月的最後一天:

select date_sub(last_day(curdate())

,interval

1month

)

last_day()函式用於獲取某個時間裡,這個月的最後一天,以上sql的時候是,取到當前月的最後一天,在通過date_sub()函式中的interval 1 month減去乙個月,得到上個月的最後一天

統計七天的資料:

select

*from

table

where

date

(時間字段)

>= date_sub(curdate(),

interval

7day

)and

date

(時間字段)

<= date_sub(curdate(),

interval

1day

)

查詢某個時間段內的資料:

select

*from

table

where date_format(時間字段,

'%y-%m-%d'

)>=

'某時間'

and date_format(時間字段,

'%y-%m-%d'

)<=

'某時間'

獲取周:

select week(curdate(),

1) 表示當前時間是今年第幾周

select week(date_sub(curdate(),

interval

7day),

1)

三十天的資料:

select

*from 表名 where date_sub(curdate(),

interval

30day

)<=

date

(時間欄位名)

;select

*from

table

where date_sub(curdate(),

interval

1month

)<=

date

(時間欄位名)

;

本月:

select

*from 表名 where date_format( 時間欄位名,

'%y%m'

)= date_format(curdate(),

'%y%m'

)

查詢乙個月

select

*from 表名 where period_diff( date_format(

now(),

'%y%m'

), date_format( 時間欄位名,

'%y%m'))

=1

mysql 時間操作 mysql操作時間

select curdate 獲取當前日期 select last day curdate 獲取當月最後一天。select date add curdate interval day curdate 1 day 獲取本月第一天 select date add curdate day curdate ...

Mysql操作時間

首先知道以下含義 now 2011 10 11 10 48 00 此刻的時間 curdate 2011 10 11 指的是零點以後的資料 date sub now interval 1 day 2011 10 10 10 57 32 昨天此刻的時間 date sub curdate interval...

mysql操作時間

select curdate 獲取當前日期 select last day curdate 獲取當月最後一天。select date add curdate interval day curdate 1 day 獲取本月第一天 select date add curdate day curdate ...