如何在mysql中获取最近的行?

时间:2011-08-25 03:58:11

标签: php mysql

让我们说我正在尝试构建一些图库的缩略图(显示5个缩略图)。如何让我的mysql显示5个缩略图,中间的缩略图将是图像被炸毁,中间左边的两个将是之前的图像,中间右边的另外两个图像将是2个以上之后的图像。

修改


我知道如何轻松获得5张这样的缩略图

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

但问题是,我没有一致的id(意思是,会有删除和插入)。它基于用户拥有的图像。

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

因此,如果用户点击了iID编号为5的图像,则缩略图应按顺序显示为1,4,5,6,10。

但是,如果用户点击缩略图编号10,缩略图也应显示:5,6,10,11,12。

3 个答案:

答案 0 :(得分:1)

试试这个

$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)

答案 1 :(得分:0)

我不知道这是否有效,但我们的想法是拥有一个名为row_number的属性。你将得到你想要的id和最后两个图像以及下一个行号。

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

我没有测试它,因为我没有运行MySQL,但我看到如何将行号放在这里:With MySQL, how can I generate a column containing the record index in a table?

答案 2 :(得分:0)

试试这个(不包括任何减法):

$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")