MySQL - next / previous ID wih cycling

风格不统一 提交于 2019-11-28 06:05:53

问题


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



来源:https://stackoverflow.com/questions/17086267/mysql-next-previous-id-wih-cycling

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!