I have an events table in my database, and each event can have up to 5 different dates. Date1 in the table is always before date2, date2 before date3 etc.
Given 2 dates in the search form, I'm trying to find the events between them.
My table is designed as follows:
id | name | date1 | date2 | date3 | date4 | date5
1 | test1 | 2013-05-24| 2013-05-25 | 0000-00-00| 0000-00-00| 0000-00-00
2 | test2 | 2013-06-01| 2013-06-08 | 2013-06-15| 2013-06-23| 2013-06-30
3 | test3 | 2013-03-15| 0000-00-00 | 0000-00-00| 0000-00-00| 0000-00-00
$datefrom , $dateto are the two variables from the search form. Now the $datefrom for example, will always search in date1 of the table. But $dateto has to search in date5, and if it is null to date4 and so on.
The best query I came up with so far is this:
SELECT * FROM events
WHERE
IF(date1 != '0000-00-00', IF(date1>='2012-12-19', 1, 0),0) = 1
AND CASE
WHEN date5!='0000-00-00' THEN IF(date5<='2012-12-31', 1, 0)
WHEN date4!='0000-00-00' THEN IF(date4<='2012-12-31', 1, 0)
WHEN date3!='0000-00-00' THEN IF(date3<='2012-12-31', 1, 0)
WHEN date2!='0000-00-00' THEN IF(date2<='2012-12-31', 1, 0)
END
But it is not working very well, for example this query returns rows with its oldest date being in 2013. I don't know if CASE is the right approach to begin with. Any ideas?? Thanks for your time!