SQL Selecting “Window” Around Particular Row

后端 未结 3 584
礼貌的吻别
礼貌的吻别 2021-01-02 11:04

It\'s quite possible a question like this has been asked before, but I can\'t think of the terms to search for.

I\'m working on a photo gallery application, and want

3条回答
  •  执笔经年
    2021-01-02 11:44

    Probably could just use a UNION, and then trim off the extra results in the procedural code that displays the results (as this will return 20 rows in the non-edge cases):

    (SELECT 
         * 
    FROM photos
       WHERE ID < #current_id#
       ORDER BY ID DESC LIMIT 10)
    UNION
      (SELECT *
       FROM photos
       WHERE ID >= #current_id#
       ORDER BY ID ASC LIMIT 10)
    ORDER BY ID ASC
    

    EDIT: Increased limit to 10 on both sides of the UNION, as suggested by le dorfier.

    EDIT 2: Modified to better reflect final implementation, as suggested by Dominic.

提交回复
热议问题