开发者

How to select all the entries from the last month?

开发者 https://www.devze.com 2023-01-02 02:49 出处:网络
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 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


If you wanted the last 30 days, this will work

SELECT * FROM `registries` 
 WHERE `reg_date` > DATE_SUB( NOW(), INTERVAL 30 DAY )


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消