mysql日期範圍查詢(兩個日期之間的記錄)

2022-06-19 08:51:10 字數 1130 閱讀 1415

**:

最近常用到mysql的datetime型別的日期範圍搜尋,總結有以下幾種方式可以,可以查詢精確到秒之間的記錄。字串日期可以直接和datetime型別之間比較,無需轉換,mysql會將字串型別日期轉換成長整型數字進行比較,當然你也可以轉換為同一型別後再比較

mysql日期與字串轉換函式

字串轉日期:str_to_date('2019-07-25 00:00:33', '%y-%m-%d %h:%i:%s')  ,走索引

日期轉字串:date_format('2019-07-25 00:00:33', '%y-%m-%d %h:%i:%s'),不走索引

舉例說明

如下表,查詢,create_time為datetime型別,查詢兩個日期範圍內的資料。

方式一、between...and(推薦)

select * from k_student where create_time  between '2019-07-25 00:00:33' and '2019-07-25 00:54:33'

方式

二、大小於號

select * from k_student where create_time >= '2019-07-25 00:00:33' and create_time <= '2019-07-25 00:54:32'

方式

三、轉換為unix_timestamp比較,create_time若加了索引,不走索引

select * from k_student where  unix_timestamp(create_time)  between unix_timestamp('2019-07-25 00:00:33') and unix_timestamp('2019-07-25 00:54:33')

mysql計算兩個日期範圍之間的所有日期

如果有許可權對資料庫進行修改操作可以使用以下方法生成日期 create table num i int insert into num i values 0 1 2 3 4 5 6 7 8 9 select adddate 2018 01 01 numlist.id as date from sel...

mysql 兩個日期區間,所有日期列表

1 專案中要用到,就去網上找了找,最後我總結一下 1.1 結構 select date format adddate 2018 02 01 interval d day y m d as date d d 1 day from 表名,select d 0 temp where adddate 201...

MySQL日期範圍內查詢

1,查詢當天 今天 的資料 select from order where to days order time to days now 2,查詢昨天的資料 select from order where to days now to days order time 13,查詢最近7天的資料 包括今...