I’m writting some scheduling code that checks for events that occuried Daily, Weekly, Fortnightly and Monthly.
So far I’ve worked out how to do Daily, Weekly, Monthly but not Fortnightly.
My table structure is…
CREATE TABLE IF NOT EXISTS `event_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`export_schedule` int(11) NOT NULL,
`import_schedule` int(11) NOT NULL,
`exception` TEXT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Resources
- [RESOLVED] Select records fortnightly
- MYSQL DATETIME Functions
- MySQL: Select data from a table where the date falls in the current Week and current Month
Say for instance the current date is 11-1-2012 (1st of November) and the last event occured on 10-20-2012 (20th October 2012) 13 days ago if I was to query that event, MySQL would return with MySQL returned an empty result set (i.e. zero rows). (Query took 0.0004 sec). With my current query.
SELECT * FROM event_log WHERE MOD(DATEDIFF(date,CURDATE()),14)=0 (Events from the current bi-week) but it doesn’t get me the any results.
How can I query for events that occured within the last fortnight?
This should do the trick:
SELECT * FROM event_log WHERE date >= DATE_SUB(NOW(), INTERVAL 14 DAY)If you ensure there is an index on the date column, this query will allow that index to be used to keep things fast as well.