I have a existing MySQL database with a column called month_year. It has date/time data in format like:- 1974 – 1982, 11/2001 – 2008, 03/2007 on, up to 1987 and 11/2001 – 02/2007.
My website user will select a date and I need to give him some options depending on whether that date meets the criteria in DB.
for example:
up to 1987 in DB means all dates upto 1987
11/2001 - 2008 means all dates between this
03/2007 on - means all dates after this.
I need a SQL query to fetch all the rows matching this criteria. I think I need some regex to achieve this but am not sure. Any help would be great!
Thanks in advance.
Added: I do not have the choice to change the database. User will select year 2011 & month 10(October). Now I have to give him options based on his input. I will have to fetch all the rows whose month_year column satisfies this.
Column looks like this:
month_year
1974 - 1982
1988 - 10/1999
1988 - 10/1999
11/1999 - 10/2001
11/2001 - 2008
11/2001 - 2008
Trying to do this comparison using regexp’s in not sensible. You will get a very complicated regular expression that neither you nor anyone else will understand the next time you look at the code.
Instead, parse the strings into their components, and do the work on the components. This generates longer code, but code that can be more easily followed.
What you have a “span” expression that you need to parse into the first and last dates. Let me give you the solution in SQL Server. I’m choosing this dialect simply because it is easier for me; I think you can readily adapt it to mysql (functions for dates and character strings seem to have different names in each database).
The following query adds columns month1, year1, month2, and year2 to the data:
You can now use these expressions to do the comparisons that you want. With one caveat: the mixing of years and years with months may give unexpected results. You need to be particular careful when a user specifies something like 9/2008 – 2010. Is this all months in 2010? Or just the first month?