We have mysql table with below columns. I am given startDate and endDate and now I have to fetch rows between those dates. Can some one please help with mysql query with how I can get those rows?
For example if startDate is November 2021 and endDate is March 2022. Then query should select rows with the months between these dates.
month | year | values |
---|---|---|
09 | 2021 | 30 |
10 | 2021 | 40 |
11 | 2021 | 90 |
12 | 2021 | 10 |
01 | 2022 | 25 |
02 | 2022 | 15 |
03 | 2022 | 89 |
2
Answers
I think the first step would be to compute a column with a proper DATE value, starting from the column you have.
For example,
STR_TO_DATE(CONCAT(year,'-', month, '-', 1), '%Y-%m-%d')
will return a proper SQL date on the 1st day of the year-month that you consider.This value can then be compared (with
<=
and>=
) with the limit dates (as requested in the comments, the answer depends on how those are represented).You can compare tuples in MySQL:
Another way is combining year and month to a single string:
This only works if year and month (at least month) are zero-filled strings.