Getting row before and after a query

前端 未结 5 2026
失恋的感觉
失恋的感觉 2021-01-16 20:15

I currently have this query

SELECT  short_url,
        type,
        file_thumbnail,
        file_embed,
        media.id,
        user,
        media.file_u         


        
5条回答
  •  心在旅途
    2021-01-16 20:58

    Do you really want the next row in the database? Is you data indexed on info.id? If not your next row might not be the item you expect. What do you do if you need to change the order of items?

    You could consider having next_id and previous_id as fields on info, and then

    SELECT
        ...
    FROM info current_info
    INNER JOIN media current_media
        ON current_info.id = current_media.id
    
    INNER JOIN info prev_info
        ON prev_info.id = current_info.previous_id 
    INNER JOIN media prev_media
        ON prev_info.id = prev_media.id
    
    INNER JOIN info next_info
        ON next_info.id = current_info.next_id 
    INNER JOIN media next_media
        ON next_info.id = next_media.id
    
    WHERE current_media.id = '$id'
    

    This has the advantages of always returning a single row. Why is that good? If there is no previous or no next how do you tell if your two returned rows are previous and current, or current and next.

    It is also more manageable as you can reorder items by changing their sibling ids.

    (WARNING: the code above may not work, i have no sql client on my laptop. But hopefully it will point you in a good direction)

提交回复
热议问题