Ryan Bañaria
Ryan Bañaria

Reputation: 88

MySQL select all dates between two dates

I have a table called schedules which contains columns day, month, year, etc. What I need is to select records between the $datefrom and $dateto. Here is my code that does not work :(

SELECT * FROM schedules WHERE CONCAT(year, month, day) BETWEEN $datefrom AND $dateto

Im not sure if this is correct. Please help.

Upvotes: 0

Views: 923

Answers (1)

fancyPants
fancyPants

Reputation: 51868

Like showdev already said in a comment, you have to cast the string that is returned from CONCAT() function to date. But consider, that no index can be used on this.

I'd suggest you create an additional column in your table with the full date. I don't know if you separated the date into 3 columns out of performance reasons, but have a try, if only one column is enough for you. Usually it's fast enough (when indexed).

If you don't want to do that and want to use indexes (if they exist at all on those 3 columns) you would have to write the query like this:

SELECT * FROM schedules WHERE 
`year` BETWEEN YEAR($datefrom) AND YEAR($dateto)
AND `month` BETWEEN MONTH($datefrom) AND MONTH($dateto)
AND `day` BETWEEN DAY($datefrom) AND DAY($dateto)

Upvotes: 1

Related Questions