MySQL - next / previous ID wih cycling

2019-01-27 04:26发布

问题:

I need to create previous / next functionality with cycling. My current solution, If I select MAX(ID) gives next as NULL.

How can I most efficiently get MIN(ID) instead of NULL(and vice versa for other direction). Of course, I can use IF or just create second query if my result is NULL, but I wonder if there is better solution.

My table has three columns

ex:

ID     foto    like

3        A      0
4        B      0
5        C      0
10       D      0

If I select ID 4 next is 5, prev is 3 //this solution I have

For ID 3, next is 4, previous is 10 //thats what I want

For previous / next I use this query

(
    SELECT MIN(`ID`) AS id 
    FROM fotos 
    WHERE `ID` > '$this->id'
    ORDER BY `like` DESC
)
UNION
(
    SELECT MAX(`ID`) AS id 
    FROM fotos 
    WHERE `ID` < '$this->id'                                            
    ORDER BY `like` DESC
)

$this->id is actually selected and displayed foto

回答1:

for next and previous id for the current foto you can do like this

SELECT COALESCE((SELECT id FROM `foto` WHERE id<'$this->id' ORDER BY DESC id LIMIT 1),
       (SELECT  MAX(id) FROM `foto`))  AS `prev`,
       COALESCE((SELECT id FROM `foto` WHERE id>'$this->id' ORDER BY id LIMIT 1 ),
       (SELECT MIN(id) FROM `foto`)) AS `next`

Hope it works fine for your needs