简体   繁体   English

如何选择上个月的所有条目?

[英]How to select all the entries from the last month?

I have a table with entries which has a DATE field. 我有一个表,其中的条目具有DATE字段。 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 如果您想要最近30天,则可以使用

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

Based on OMG Ponies' query with corrections: 基于OMG Ponies的查询并进行更正:

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. 尽管查询的性能不是很好,但由于它将对两个计算出的值进行JOIN操作。 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) 另一方面,您可以通过先查询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. 使用first_day作为上一个查询结果的占位符。 Provided you indexed reg_date, this should run pretty fast. 如果您为reg_date编制了索引,则此运行速度应该很快。

Note: LAST_DAY is a MySQL only function. 注意:LAST_DAY是仅MySQL的函数。

This will give you all records for last month (May): 这将为您提供上个月(5月)的所有记录:

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 从表名中选择[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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM