tags:

views:

47

answers:

3

I wanna get rows in recent date, this week or month, etc. suppose the table has a field named: product_date.

+4  A: 

To get the rows in the last month, you could use something like:

SELECT * FROM table WHERE product_date >= DATE_SUB(NOW(), INTERVAL 1 MONTH);

Or for the last week:

SELECT * FROM table WHERE product_date >= DATE_SUB(NOW(), INTERVAL 1 WEEK);
mopoke
+2  A: 

For within the last seven days:

WHERE product_date BETWEEN DATE_ADD(NOW(), INTERVAL -7 DAY) AND NOW() 

For the last month:

WHERE product_date BETWEEN DATE_ADD(NOW(), INTERVAL -1 MONTH) AND NOW()
OMG Ponies
thank you, OMG......
lovespring
A: 

While mopoke's solution gets results from last 30 or 7 days, this gives you results for current month only:

SELECT * FROM table WHERE DATE_FORMAT(product_date, '%c-%Y') = DATE_FORMAT(CURDATE(), '%c-%Y');

Or for current week:

SELECT * FROM table WHERE DATE_FORMAT(product_date, '%u-%Y') = DATE_FORMAT(CURDATE(), '%u-%Y');
Tatu Ulmanen
Using a function (in this case DATE_FORMAT) means that an index, if one existed on the `product_date` column, could not be used.
OMG Ponies
That is correct, but on smaller datasets that's an acceptable drawback if you *must* have the results for current week or month - at least I'm not aware of any other method.
Tatu Ulmanen
thank you. Tatu......
lovespring