简体   繁体   English

MySQL SELECT WHERE DATE大约是X天前

[英]MySQL SELECT WHERE DATE is approx X days ago

I have a table containing a date column. 我有一个包含日期列的表。

The table data is inserted via a cron job at irregular intervals, and not daily. 表格数据是通过cron作业以不定期的间隔(而不是每天)插入的。

I'd like to select only the row that is closest to X days ago. 我只想选择最接近X天前的行。

So for example if its June 30th and there is no entry for June 25th I'd like it to grab the entry from June 26th or 24th (whichever is newest and closest in time to 5 days ago), if there are no entries on the 26th or 24th then to look for 27th or 23rd, etc... 因此,例如,如果6月30日且6月25日没有条目,我希望它从6月26日或24日(以最新的时间和最近的时间到5天前)为准,如果该条目没有26日或24日,然后寻找27日或23日,依此类推...

The date is stored as YYYY-MM-DD HH:MM:SS. 日期存储为YYYY-MM-DD HH:MM:SS。

Any help is much appreciated :) 任何帮助深表感谢 :)

Assuming the TIMESTAMP column is insertion_ts and ? 假设TIMESTAMP列是insertion_ts? is bound to the DATE or TIMESTAMP you desire: 绑定到您想要的DATE或TIMESTAMP:

   SELECT *
    FROM tbl
ORDER BY 
         -- We want the closest insertion_ts to our target date ...
         ABS(TIMESTAMPDIFF(SECOND, ?, insertion_ts)) ASC,
         -- ... and will favor the more recent in the unlikely event of a tie
         TIMESTAMPDIFF(SECOND, ?, insertion_ts) DESC
   LIMIT 1;

Something like : 就像是 :

SELECT   id, date, ....
FROM     tbl
WHERE    date <= [your date YYYY-MM-DD HH:MM:SS]
ORDER BY date DESC
LIMIT 1
SELECT *
FROM `table`
ORDER BY ABS(DATEDIFF(`date`, (DATE_SUB(NOW(), INTERVAL X DAY)))) ASC
LIMIT 1

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

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