tags:

views:

713

answers:

3

I have a MySQL member table, with a DOB field which stores all members' dates of birth in DATE format (Notice: it has the "Year" part)

I'm trying to find the correct SQL to:

  • List all birthdays within the next 14 days

and another query to:

  • List all birthdays within the previous 14 days

Directly comparing the current date by:

(DATEDIFF(DOB, now()) <= 14 and DATEDIFF(DOB, now()) >= 0)

will fetch nothing since the current year and the DOB year is different.

However, transforming the DOB to 'this year' won't work at all, because today could be Jan 1 and the candidate could have a DOB of Dec 31 (or vice versa)

It will be great if you can give a hand to help, many thanks! :)

A: 

There are a number of options, I would first try to transform by number of years between current year and row's year (i.e. Add their age).

Another option is day number within the year (but then you have still to worry about the rollover arithmetic or modulo).

Cade Roux
+1  A: 

Easy,

We can obtain the nearer birthday (ie the birthday of this year) by this code:

dateadd(year,datediff(year,dob,getdate()),DOB)

use this in your compares ! it will work.

tekBlues
I'm still unsure about it... mind to convert it to mysql version? many thanks!
Unreality
You are right, sorry about it, just typed without thinking, just so used to SQL Server. DATE_ADD is equal to SQL Server's DATEADD. Is there an equivalent to DATEDIFF in mySQL, ie something that gives me the distance of two dates in years?
tekBlues
+1  A: 

My first thought was it would be easy to just to use DAYOFYEAR and take the difference, but that actually gets kinda trick near the start/end of a yeay. However:

WHERE 
DAYOFYEAR(NOW()) - DAYOFYEAR(dob) BETWEEN 0 AND 14 
OR DAYOFYEAR(dob) - DAYOFYEAR(NOW())  > 351

Should work, depending on how much you care about leap years. A "better" answer would probably be to extract the DAY() and MONTH() from the dob and use MAKEDATE() to build a date in the current (or potential past/following) year and compare to that.

Eli
Thanks I'm gonna try that :)
Unreality
i believe it works, thanks :)
Unreality