简体   繁体   English

Mysql 获取日期之间的行 在年份和月份列之间拆分

[英]Mysql get rows between date split between year and month columns

I have a table with a year and month in different columns, and I need to find all rows between 3 months ago and now.我有一张表,在不同的列中有年份和月份,我需要找到 3 个月前和现在之间的所有行。

SELECT * FROM `table` 
 WHERE DATE(CONCAT(`year`, '-', `month`, '-01')) >= 
          DATE_FORMAT(NOW() - INTERVAL 3 MONTH, '%Y-%m-01')

It just seems rather verbose, and possibly inefficient as this is a very large table.它看起来相当冗长,并且可能效率低下,因为这是一个非常大的表。 Is there a better way to do this?有一个更好的方法吗?

There isn't much optimization to be had when the date is stored as separate fields, but I would re-write your query as:当日期存储为单独的字段时,没有太多优化,但我会将您的查询重写为:

SELECT * 
  FROM `table` 
 WHERE STR_TO_DATE(`year`+ '-'+ `month` + '-01', '%Y-%m-%d') >= DATE_SUB(NOW(), INTERVAL 3 MONTH)

The concatenation renders indexing on the year and month columns useless.连接使得对yearmonth列的索引变得无用。

For more info about MySQL date functions, see: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html For more info about MySQL date functions, see: http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html

Well, I had the same issue and I have figured what I think is the solution for this case.好吧,我遇到了同样的问题,我已经想出了我认为是这种情况的解决方案。

SELECT * 
FROM table
WHERE (month >= (month(curdate()) - 3 AND year >= year(curdate())) 
      AND (month >= month(curdate()) AND year >= year(curdate())))

Supposing you have columns named year and month.假设您有名为年和月的列。

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

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