简体   繁体   中英

mysql select between two dates / times

I have a mysql db that has a date field as well as a time field. I need to select the following argument from the db.

select from spiff where date is between 02/01/2016 and time is equal to or grater then 12:00:00 and date 02/08/2016 and time is equal too or less then 11:59:59

so in simple forum i want to select everything from 7 days ago till today from noon to noon where 12;00:00 is the cut off time.

I have this code but it doesnt do quite what i want

SELECT * 
FROM spiff 
WHERE `date` BETWEEN '" . $week_before . "' AND  '" . $today . "' AND time <= '12:00:00'  
ORDER by id DESC

That's not going to work. You can't store the date and time in separate fields, then search by both. You're excluding all times LATER than "noon", which means that if you have these dates/times:

02/02/2016 13:00    excluded
02/03/2016 10:00    included
02/04/2016 17:59    excluded

Even those the dates fall within your specified range, the 13:00 and 17:59 ones are EXCLUDED becomes they're NOT < '12:00:00'

You need to store the dates as a single datetime field, and then your query becomes a trivial:

SELECT ... WHERE datetimefield BETWEEN '2016-02-01 12:00:00' AND '2016-02-08 11:59:59'

And note that for these sorts of date/time comparisons to work, you HAVE to be using mysql's actual date/time fields, and mysql's date-as-time string format: yyyy-mm-dd . If your dates are stored as mm/dd/yyyy , then they're NOT dates, they're strings, and mysql's string comparison rules apply, which means that

'10/11/2015' > '09/01/1970' -> TRUE

because 10 is larger than 09 .

The problem is that you have the date and the time parts in separate fields. As a result of the AND time <= '12:00:00' condition in the where clause, MySQL will return records from the morning for all affected dates.

The best solution would be to combine the 2 fields into one with datetime data type. This way the where clause would be:

...`datime_field` BETWEEN '" . $week_before_noon . "' AND  '" . $today_noon . "'

The 2 php variables would contain a valid datetime expression in the format of YYYY-MM-DD hh:mm:ss

The alternative solution is to combine the values from the 2 fields on the fly, but this way you cannot use indexes to speed up the search:

... date + time BETWEEN '" . $week_before . " 12:00:00' AND  '" . $today . " 12:00:00'

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