SQL Selecting “Window” Around Particular Row

后端 未结 3 601
礼貌的吻别
礼貌的吻别 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:36

    This is standard "Row ordering" problem... If your database has rowId capability you can use that, otherwise you need a subquery that counts the numnber of rows with Ids less than the id of the current row... like this:

    -- asssuming @Id is value of id in the "middle"

     Select *  From Photos P
     Where (Select Count(*) From Photos
             Where id <= P.Id)
         Between (Select Count(*) From Photos
                  Where id < @Id) - 4
            And  (Select Count(*) From Photos
                  Where id < @Id) + 4
    

    As a comment raised the album issue you would want to add album predicate to each subquery

       Select *  From Photos P
       Where (Select Count(*) From Photos
              Where album = @album
                And id <= P.Id)
         Between (Select Case When Count(*) < 4 
                          Then 4 Else Count(*) End
                  From Photos
                  Where album = @album
                     And id < @Id) - 4
            And  (Select Case When Count(*) < 4 
                          Then 4 Else Count(*) End
                  From Photos
                  Where album = @album
                      And id < @Id) + 4
    

提交回复
热议问题