MySQL – How to Get Closest Previous Date

datedatetimeMySQL

I need to get the posts closest to a date.

SELECT id
     , datetime
  FROM dates
 WHERE id != 150003
   AND datetime > FROM_UNIXTIME(1549622615)
 ORDER BY datetime
 LIMIT 1

Returns a correct result:

{"id":"150015","datetime":"2019-04-13 17:47:55"}]

but when I change to "datetime < FROM_UNIXTIME(1549622615)" I get the result:

{"id":"1","datetime":"1970-01-10 12:06:07"} 

when there are many posts closer to the datetime.

Any insights why?

Best Answer

When you change it to datetime < FROM_UNIXTIME(1549622615) you also need to change the sort order to ORDER BY datetime DESC to get the closest date.