views:

109

answers:

4

I have a table with entries which has a DATE field. Each entry has a distinct date. I'd like to select all the entries from the last month registred in the database. How?

I tried:

SELECT * 
  FROM registries 
 WHERE reg_date = DATE_FORMAT(MAX(reg_date), "%m")` 

...without success

+2  A: 

If you wanted the last 30 days, this will work

SELECT * FROM `registries` 
 WHERE `reg_date` > DATE_SUB( NOW(), INTERVAL 30 DAY )
Kerry
This. Use this.
Entendu
A: 

Probably something like SELECT * FROM registries WHERE reg_date >= DATE_SUB(reg_date, INTERVAL 1 MONTH);

Yasir Arsanukaev
A: 

This will give you all records for last month (May):

SELECT [col,] DATEDIFF(TIMESTAMP, 2010-05-01 00:00) dif1, DATEDIFF(TIMESTAMP, 2010-05-31 00:00) dif2 FROM tablename HAVING dif1 >= 0 AND dif2 <= 0

Muleskinner
+1  A: 

Based on OMG Ponies' query with corrections:

SELECT 
  r.*
FROM 
  registries AS r
JOIN (
  SELECT 
    MAX(t.reg_date) AS max_date
  FROM 
    registries AS t) AS t 
ON DATE_FORMAT(t.max_date, '%Y-%m') = DATE_FORMAT(r.reg_date, '%Y-%m')

Though the performance of the query wouldn't be excellent, since it would operate the JOIN on two calculated values. I believe it can still perform decently unless you start hitting millions of records.

On the other hand, you could probably run it faster by querying first for the MAX(reg_date)

SELECT 
  CONCAT(DATE_FORMAT(MAX(r.reg_date), "%Y-%m"), '-01') AS first_day
FROM 
  registries AS r

And then injecting the result in a query:

SELECT 
  r.*
FROM 
  registries AS r
WHERE
  r.reg_date BETWEEN '<first_day>' AND LAST_DAY('<first_day>')

With first_day as a place holder for the previous' query result. Provided you indexed reg_date, this should run pretty fast.

Note: LAST_DAY is a MySQL only function.

Guillaume Bodi