Select a row and rows around it

后端 未结 7 2127
庸人自扰
庸人自扰 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

    I'm agree with the answer suggested by malonso(+1), but if you try it with id= 1, you will get only 5 thumbnails. I don't know if you want this behaviour. If you want always 10 thumbs, you can try:

    select top 10 * from media where id > 7 - 4
    

    The problem is that select top is database dependent (in this case is a sql server clause). Other database has similar clauses:

    Oracle:

    SELECT *  media
    FROM media
    WHERE ROWNUM < 10
    AND id > 7 - 4
    

    MySQL:

    SELECT * 
    FROM media
    WHERE id > 7 - 4
    LIMIT 10
    

    So maybe you can use the last one.

    If we do it, we will have the same problem if you want the last 10 thumbs. By example, If we have 90 thumbs and we give an id=88 ... You can solve it adding an OR condition. In MySQL will be something like:

    SELECT * 
        FROM media
        WHERE id > 7 - 4
        OR (Id+5) > (select COUNT(1) from media)
        LIMIT 10
    

提交回复
热议问题