tags:

views:

460

answers:

3

Here's my query:

SELECT *
FROM daily_records 
AND date = DATE_SUB(CURDATE(), INTERVAL 1 DAY)

I use this to generate a report of everything that happened yesterday. This works great, Tuesday-Friday. However, on Mondays, I want it to be able to search back to Friday (the previous business day, eg INTERVAL 3 DAY).

Is there a way to do this in mySQL? Or do I just need to check the day of the week in PHP before writing the query?

+2  A: 

You could do...

SELECT *
FROM daily_records
WHERE date = IF(DAYOFWEEK(CURDATE()) = 2, DATE_SUB(CURDATE(), INTERVAL 3 DAY), DATE_SUB(CURDATE(), INTERVAL 1 DAY))
VoteyDisciple
Same-second answers!
Greg
+2  A: 

This should do it:

SELECT * FROM daily_records AND date =
DATE_SUB(CURDATE(), INTERVAL IF(DATE_FORMAT(NOW(), '%w') = 1, 3, 1) DAY)
Greg
I like this ... I think I need to change the 5 in the if statement so it reads:IF(DATE_FORMAT('%w', NOW()) = 1, 3, 1) because NOW() would be Monday, not Friday. Thanks!
Jen
Another note - I just researched DAYOFWEEK() and DATE_FORMAT() and they use different indexes. With DAYOFWEEK(), Sunday=1. With DATE_FORMAT(), Sunday=0. Anyone know why?!?
Jen
That's true... DAYOFWEEK follows ODBC, DATE_FORMAT follows... ISO?
Greg
This is mostly just a note to myself, but possibly helpful to others as well ... the parameters for the date_format function are backwards. It should be DATE_FORMAT(NOW(), '%w') ...
Jen
Oops - fixed, thanks
Greg
A: 
mysql> create function PREV_BIZ_DATE ()
    -> returns DATE
    -> return (CURRENT_DATE() - interval if(DAYOFWEEK(CURRENT_DATE()) = 2, 3, 1) day);

mysql> SELECT * FROM daily_records WHERE date = PREV_BIZ_DATE();
pilcrow