简体   繁体   中英

How to SELECT a date between two dates

How can I select from mysql with php a range between 2 dates? The working day, start for example, at 7:00 am of 2022-01-01 and ends at 2:00 am of 2022-01-02. I want that all collected datas from 00:00 to 2:00 am of 2022-01-02 are grouped inside previous date.

Now I use this query

 SELECT date_format(dateAdded,"%m-%d") as mth,COUNT(productID) as total, productID FROM statisticsNW WHERE userID = "35" AND productID = "1193'" AND YEAR(dateAdded) = "2022" AND month(dateAdded) = "01" GROUP by year(dateAdded),month(dateAdded), day(dateAdded) ORDER by year(dateAdded),month(dateAdded)

and the result is this but the "total" is wrong because is from 00:00 to 23:59 of the same day. The correct query the I want is from 7:00 to 6:59 of the next day. But from 00:00 to 6:59 datas must be counted in the previous day.

在此处输入图像描述

you can add 5 hours to the start_time and end_time, so the it appears the shift starts at midnight

select DATEDIFF(HH,cast('2022-01-24 19:00:00' as datetime),cast('2022-01-25 00:00:00' as datetime)) as time_5_hrs

结果

select dateadd(HOUR,5,cast('2022-01-02 19:00:00' as datetime)) as starttime, dateadd(HOUR,5,cast('2022-01-03 02:00:00' as datetime)) as endtime,datediff(HH,dateadd(HOUR,5,cast('2022-01-02 19:00:00' as datetime)),dateadd(HOUR,5,cast('2022-01-03 02:00:00' as datetime))) diff

在此处输入图像描述

By doing this you can get both date are the same and you will be able to group it as single day.

I have solved

SELECT DATE_SUB(DATE_ADD("2017-06-15 5:30:00", INTERVAL 24 HOUR), INTERVAL 1 MINUTE); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM