简体   繁体   中英

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.

I'd like to select only the row that is closest to X days ago.

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...

The date is stored as YYYY-MM-DD HH:MM:SS.

Any help is much appreciated :)

Assuming the TIMESTAMP column is insertion_ts and ? is bound to the DATE or TIMESTAMP you desire:

   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

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