Mysql Select Next & Prev row not order by id

前端 未结 2 1306
星月不相逢
星月不相逢 2021-02-09 07:22

I have a query ordered by NAME that return smt like this:

 ID     NAME
2121927 AAA
2123589 AAB
2121050 AAC
2463926 BBB ---> known ID
2120595 CCC
2122831 DDD
2         


        
2条回答
  •  名媛妹妹
    2021-02-09 08:00

      SELECT *,
             'next'
        FROM table
       WHERE `name` > 'BBB'
    ORDER BY `name`
       LIMIT 1
    
    UNION
    
      SELECT *,
             'previous'
        FROM table
       WHERE `name` < 'BBB'
    ORDER BY `name` DESC
       LIMIT 1
    

    If you don't know particular BBB name field value - you could replace it with subquery like SELECT name FROM table WHERE id = 42, where 42 is the known ID value.

提交回复
热议问题