1

I figure out how I can get the next adid using this:

SELECT adid FROM table WHERE adid > $current_adid ORDER BY adid 
LIMIT 1

However, I am not sure how to get the previous adid. I tried changing WHERE adid < $current_adid but it didn't do the trick. What should I use to get a previous record from the SQL table?

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 2
    Possible duplicate of [How to get next/previous record in MySQL?](https://stackoverflow.com/questions/1446821/how-to-get-next-previous-record-in-mysql) – Script47 Jun 07 '18 at 02:36

1 Answers1

2

You need to reverse more than just the comparison:

SELECT adid
FROM table
WHERE adid < $current_adid
ORDER BY adid DESC
LIMIT 1;

The ORDER BY direction also needs to be reversed.

You could also replace these with:

SELECT MIN(adid)
FROM table
WHERE adid > $current_adid;

SELECT MAX(adid)
FROM table
WHERE adid < $current_adid;

The aggregation functions might make the logic clearer.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786