简体   繁体   中英

Birthday users between current date and next 7 days not working with between condition

I have write a simple query to check birthday between current date and next 7 days which works fine few days before but now its returning 0 result the reason I've found is its searching between 12-29 to 01-05 so I think that's why its not returning here's the query :

SELECT `U`.`FirstName`, `U`.`LastName`, `U`.`UserGUID`, `U`.`ProfilePicture`
WHERE DATE_FORMAT(U.DOB,'%m-%d') 
BETWEEN DATE_FORMAT('2015-12-29 07:08:01','%m-%d') 
        AND DATE_FORMAT('2016-01-05','%m-%d')

Change query as:

  SELECT `U`.`FirstName`, `U`.`LastName`, `U`.`UserGUID`, `U`.`ProfilePicture` WHERE DATE_FORMAT(U.DOB,'%m-%d') BETWEEN date_format(DATE_FORMAT('2015-12-29 07:08:01','%y-%m-%d'),'%m-%d') AND Date_Format(DATE_FORMAT('2016-01-05','%y-%m-%d'),'%m-%d') 

You can use a string comparison by DATE_FORMAT(U.DOB,'%Y%m') .

DATE_FORMAT(U.DOB,'%Y%m') should return dates like: YYYYMM . You would also need to change the format of your variables or use the same method on them.

SELECT `U`.`FirstName`, `U`.`LastName`, `U`.`UserGUID`, `U`.`ProfilePicture` 
WHERE DATE_FORMAT(U.DOB,'%Y%m') >= DATE_FORMAT('2015-12-29 07:08:01','%Y%m') AND 
DATE_FORMAT(U.DOB,'%Y%m') <= DATE_FORMAT('2016-01-05','%Y%m')

You can get like below

SELECT `U`.`FirstName`, `U`.`LastName`, `U`.`UserGUID`, `U`.`ProfilePicture` WHERE DAY(cast(U.DOB as datetime)) BETWEEN DAY(cast('2015-12-29 07:08:01' as datetime)) AND DAY(cast('2016-01-05' as datetime)) AND 
MONTH(CAST(U.DOB AS DATETIME)) BETWEEN MONTH(CAST('2015-12-29 07:08:01'AS DATETIME)) AND MONTH(CAST('2016-01-05' AS DATETIME)) 

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