简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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