2

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.

4

2 回答 2

8

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
于 2013-07-10T22:06:21.530 回答
0

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.

于 2013-07-10T21:59:42.617 回答