Select a row and rows around it

后端 未结 7 2156
庸人自扰
庸人自扰 2020-12-19 15:05

Ok, let\'s say I have a table with photos.

What I want to do is on a page display the photo based on the id in the URI. Bellow the photo I want to have 10 thumbnails

7条回答
  •  执笔经年
    2020-12-19 15:29

    Only one ORDER BY clause can be defined for a UNION'd query. It doesn't matter if you use UNION or UNION ALL. MySQL does support the LIMIT clause on portions of a UNION'd query, but it's relatively useless without the ability to define the order.

    MySQL also lacks ranking functions, which you need to deal with gaps in the data (missing due to entries being deleted). The only alternative is to use an incrementing variable in the SELECT statement:

    SELECT t.id, 
           @rownum := @rownum+1 as rownum 
      FROM MEDIA t, (SELECT @rownum := 0) r
    

    Now we can get a consecutively numbered list of the rows, so we can use:

    WHERE rownum BETWEEN @midpoint - ROUND(@midpoint/2) 
                     AND @midpoint - ROUND(@midpoint/2) +@upperlimit
    

    Using 7 as the value for @midpoint, @midpoint - ROUND(@midpoint/2) returns a value of 4. To get 10 rows in total, set the @upperlimit value to 10. Here's the full query:

    SELECT x.* 
      FROM (SELECT t.id, 
                   @rownum := @rownum+1 as rownum 
              FROM MEDIA t, 
                   (SELECT @rownum := 0) r) x
     WHERE x.rownum BETWEEN @midpoint - ROUND(@midpoint/2) AND @midpoint - ROUND(@midpoint/2) + @upperlimit
    

    But if you still want to use LIMIT, you can use:

      SELECT x.* 
        FROM (SELECT t.id, 
                     @rownum := @rownum+1 as rownum 
                FROM MEDIA t, 
                     (SELECT @rownum := 0) r) x
       WHERE x.rownum >= @midpoint - ROUND(@midpoint/2)
    ORDER BY x.id ASC
       LIMIT 10
    

提交回复
热议问题