SQL Selecting “Window” Around Particular Row

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

    If you are using SQL Server, you can use the row_number() function to give you the row order index and do something like this:

    declare @selected_photo integer;
    set @selected_photo = 5;
    
    declare @buffer_size integer;
    set @buffer_size = 2;
    
    select
       ph.rownum,
       ph.id
    from
       (select row_number() over (order by Id) as rownum, * from Photos) as ph
    where
       ph.rownum between case
                             when @selected_photo - @buffer_size < 1 then 1
                             else @selected_photo - @buffer_size
                          end
                          and @selected_photo + @buffer_size
    

    Edit: Here is an article on simulating the row_number() function in MySQL, combining that with this might get you what you need - I'd try it but don't have a MySQL db handy to play with at work. :-)

    http://www.xaprb.com/blog/2006/12/02/how-to-number-rows-in-mysql/

提交回复
热议问题