开发者

How can I get the nearest rows in mysql?

Lets say I'm trying to build a thumbnail of some gallery (5 thumbnails showing). How can I get my mysql to display 5 thumbnails, the middle thumbnail will be the image blown up, and开发者_开发问答 the two on the left of the middle will be previous images, and the two other images on the right of the middle will be 2 more images after.

EDIT


I know how to easily get 5 thumbnails with something like this

$sqlThumb = mysql_query("SELECT iID,thumbnails,userID FROM images WHERE userID = ".$_SESSION['userID']." ORDER BY iID ASC LIMIT 1,5");

But the thing is, I dont have a consistent id (meaning, there will be deleting and inserting). It is based on the images that the user has.

iID            userID 
-----          --------
1              5
2              4
3              4
4              5
5              5
6              5
10             5
11             5
12             5

So if a user clicks an image which shoes iID number 5, the thumbnail should show like this in order, 1,4,5,6,10.

However, also if a user clicks on thumbnail number 10, the thumbnail should show: 5,6,10,11,12.


Try this

$offset = $current_id-3;

 (SELECT * FROM TBL WHERE id < '$current_id'    limit '$offset',2 )
 union( SELECT * FROM TBL WHERE id = '$current_id') 
 union (SELECT * FROM TBL WHERE id > '$current_id' limit 2)


I don't know if this works, but the idea is to have an attribute called row_number. You will get the image you want by the id and the two last and the two next by the row number.

SELECT iID,thumbnail FROM image_collection,
   (SELECT iID, thumbnail, row_number
   FROM
      (SELECT iID,thumbnail,
      @curRow := @curRow + 1 AS row_number
      FROM image
      WHERE userID = 5
      ORDER BY iID) as image_collection
   WHERE s_image.iID = 10) as image_selected
WHERE image_collection.row_number BETWEEN image_selected.row_number - 2 AND image_selected.row_number + 2

I don't tested it because I don't have MySQL running, but I see how to put the row number here: With MySQL, how can I generate a column containing the record index in a table?


Try this one (doesn't include any subtraction):

$id = 5;
$user_id = $_SESSION['userID'];

$sqlThumb = mysql_query("
SELECT iID FROM images WHERE userID = ".$user_id." AND iID = ".$id."
  UNION (SELECT iID FROM images WHERE userID = ".$user_id." AND iID < ".$id." ORDER BY iID DESC LIMIT 2) 
  UNION (SELECT iID FROM images WHERE userID = ".$user_id." AND iID > ".$id." ORDER BY iID ASC LIMIT 2) 
  ORDER BY iID ASC")
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜