I was wondering how to select next and previous rows from a mysql database with reference to my currently selected row.
I found this question on SO How to get next/previous record in MySQL? but in this case the select is done based on higher and lower id from the reference. I would like to use earlier or later timestamp instead of ids.
There is no reason for using subqueries.
Next:
SELECT * FROM `my_table`
WHERE `the_timestamp` > 123456
ORDER BY `the_timestamp` ASC
LIMIT 1
Prev:
SELECT * FROM `my_table`
WHERE `the_timestamp` < 123456
ORDER BY `the_timestamp` DESC
LIMIT 1
Based on the article you linked to, you can use:
SELECT *
FROM `my_table`
WHERE `the_timestamp` = (
SELECT MIN(`the_timestamp`)
FROM `my_table`
WHERE `the_timestamp` > 1373493634
);
It's formatted for readability. Replace the timestamp I used (1373493634) with the timestamp you want to find the next record after.
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.