查找此ID旁边是否有可用的ID?

时间:2014-09-29 11:15:02

标签: php mysql attachment

我想知道的是在SQL查询中有什么方法可以找到当前ID上方或旁边是否有任何ID?这是一个更加编程的SQL查询草图:

假设我在帖子中有5 image attachments,我点击number 3打开一个PopUp窗口,现在想知道是否有其他aid可用,以便我可以显示NEXT按钮吗?

$current_aid = '3';
$pid = '313'; // Thats fixed value of post

$query = $db->query("
    SELECT aid
    FROM attachments
    WHERE aid != '{$current_aid}' AND pid = '{$pid}'
    ORDER BY aid DESC
");

我怎样才能找到它?

2 个答案:

答案 0 :(得分:2)

查询

   SELECT aid FROM attachements WHERE aid > {$current_aid} AND pid = {$pid} ORDER BY aid DESC LIMIT 1;

然后在此处添加其他查询逻辑。

答案 1 :(得分:1)

您可以尝试此查询以获取下一个和上一个链接

SELECT 
(SELECT aid FROM attachments WHERE aid > '{$current_aid}' AND pid = '{$pid}' LIMIT 1)
AS next_link,
(SELECT aid FROM attachments WHERE aid < '{$current_aid}' AND pid = '{$pid}' ORDER BY aid DESC LIMIT 1) 
AS prev_link FROM attachments