Forum Moderators: open
im trying to retrieve rows from my table where the month is last month, but it returns zero results.
i currently have:
$result = mysql_query('SELECT * FROM tickets WHERE (month(created) = (month(now())-1))');
anyone know why it might not be working? any help greatly appreciated thanks again.
"created" is the name of the column in the table which holds the date....just to make things clearer
[edited by: resistanceM at 11:59 pm (utc) on Jan. 5, 2008]
now() includes the full date and time stamp. I'd only use it if that's the format of your fields. I'd use curdate() instead.
I would use date_sub.
select * from tickets where created = date_sub(curdate(), interval 1 month);
However, this will only return fields for tickets sold exactly a month ago from today. If you want last month's tickets up to today,
select * from tickets where created >= date_sub(curdate(), interval 1 month) and created <= date_sub(curdate(), interval 1 day);
select * from tickets where created >= date_sub(curdate(), interval 1 month) and created <= date_sub(curdate(), interval 1 day);
Note that this is the only solution given that can make use of an index on "created".
Any solution that only examines a date part (rather than comparing date values) is going to require an exhaustive read of the entire table.