I have a constant timestamp of say 18040986 (in my query its $readtime).
Now my table has many entries and each entry has its own timestamp.
I wanted to efficiently search to find the timestamp which is greater then the constant timestamp, but is also the nearest to that. (In essence I am trying to find the first unread entry by a user)
Now the trick is, that say there have been no entries made then I would love to get the nearest timestamp that is less then the current timestamp (ie. the nearest old entry that has already been read)
I was hoping for help with the query to achieve that. The basic queries I have made so far have either been highly inefficient and have slowed my server to a crawl or have been inaccurate. The query I am using for now is this
SELECT postid
FROM theposts
WHERE category = '$tid' AND visible='1' AND dateline > '$readtime'
LIMIT 1
But I am worried that the above query wont actually return the next nearest postid that is greater then my readtime if for some reason my table has entries out of order one day
The following recommendations will help you in your SQL tuning process.
You'll find 3 sections below:
ALTER TABLE `theposts` ADD INDEX `theposts_idx_category_visible_dateline` (`category`,`visible`,`dateline`);
SELECT
theposts.postid
FROM
theposts
WHERE
theposts.category = '$tid'
AND theposts.visible = '1'
AND theposts.dateline > '$readtime' LIMIT 1