简体   繁体   中英

Get birthday from customers between now and a week MYSQL

Im trying to get the records from the database where the customers birthday is between now and a week. I've tried a lot of options and i'm searching for over an hour but i can't find a working solution. I'm using MYSQL 5.7.19. This is my query

SELECT firstname, lastname, IF(housenumber_addition = "", CONCAT(housenumber,housenumber_addition ), housenumber_addition ) AS adres, sex
FROM customer
WHERE DATE(birthdate) BETWEEN NOW() AND NOW() + INTERVAL 7 DAY

Picture of the data: 数据 Picture of the structure: 结构体

It's in dutch :( I also need to get the new age from the customer if it's birthday is between now and a week

Hopefully someone could give me a good and working answer

Thanks in advance

Your problem is that the birthdate is not in the current year, so your test cannot be true. You need to convert the birthdate into a value in the current year, which you can do by this:

STR_TO_DATE(CONCAT(YEAR(NOW()), '-', MONTH(birthdate), '-', DAY(birthdate)), '%Y-%m-%d')

So your query becomes:

SELECT firstname, lastname, IF(housenumber_addition = "", CONCAT(housenumber,housenumber_addition ), housenumber_addition ) AS adres, sex
FROM customer
WHERE STR_TO_DATE(CONCAT(YEAR(NOW()), '-', MONTH(birthdate), '-', DAY(birthdate)), '%Y-%m-%d') BETWEEN NOW() AND NOW() + INTERVAL 7 DAY

Update

As @GordonLinoff points out, this doesn't work if the week overlaps a year end and the birthdate is in the beginning of January (eg NOW() = '2018-12-28' and birthdate = '1985-01-02'). To make that case work, it is necessary to also check on the birthdate in YEAR(NOW())+1 ie

SELECT firstname, lastname, IF(housenumber_addition = "", CONCAT(housenumber,housenumber_addition ), housenumber_addition ) AS adres, sex
FROM customer
WHERE STR_TO_DATE(CONCAT(YEAR(NOW()), '-', MONTH(birthdate), '-', DAY(birthdate)), '%Y-%m-%d') BETWEEN NOW() AND NOW() + INTERVAL 7 DAY OR
    STR_TO_DATE(CONCAT(YEAR(NOW())+1, '-', MONTH(birthdate), '-', DAY(birthdate)), '%Y-%m-%d') BETWEEN NOW() AND NOW() + INTERVAL 7 DAY

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