简体   繁体   中英

Mysql date search between 2 dates returns 0 rows

Basically i want to get the people who checked in after given date and checked out before or on the same day of the check out date. Here are some queries i have tried.

SELECT * FROM `booking`
        WHERE (check_in BETWEEN '2017-09-10' AND '2017-09-21')
          AND (check_out between '2017-09-10' and '2017-09-21')

which returns 0 rows and

SELECT * FROM `booking`
        WHERE check_in >= '2017-09-10' AND check_out <= '2017-09-21'

returns 0 rows. I have a customer check in on 2017-09-18 and check out on 2017-09-21. How to resolve this ?

I don't know the values in your DB but a common mistake that you may have made is assume that your database 2017-09-21 entry will fit into (check_out between '2017-09-10' and '2017-09-21') . Your 2017-09-21 is in fact 2017-09-21 00:00:00. Most probably your database date has some non-zero hours and minutes to it which makes it LARGER than 2017-09-21 00:00:00.

For eg 2017-09-21 05:06:23 is larger than 2017-09-21 00:00:00 and will not fit into your condition.

Try:

SELECT * FROM `booking`
        WHERE (check_in >= '2017-09-10' AND check_in < '2017-09-22')
          AND (check_out >= '2017-09-10' AND check_out <'2017-09-22')

Try like this:

SELECT * FROM `booking`
        WHERE DATE(check_in) >= '2017-09-10' AND DATE(check_out) <= '2017-09-21'

Use mysql date format function in check in and check out field

SELECT * FROM `booking`
WHERE DATE_FORMAT(check_in,'%Y-%m-%d') >= '2017-09-10' AND 
DATE_FORMAT(check_out,'%Y-%m-%d') <= '2017-09-21'

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