PHP / MYSQL查询:获取上下结果!

时间:2011-02-28 21:00:01

标签: php mysql views

我不知何故需要以下方法:

用户位于某个博客页面现在我想让他有能力移动:

到下一个更受欢迎的页面或下一个不太受欢迎的页面。意思是这样的:

[PAGE 5] | [PAGE 3 (User is here)] | [PAGE 2]

(第1页=最受欢迎,第3页=最不受欢迎)。我的MySQL表看起来像这样:

[ID] [VIEWS]
[1] [1000]
[2] [2560]
[3] [3200]
[4] [200]
[5] [4000]

我的问题是具体的查询。在这种情况下,唯一给定的变量是ID:2。也许你可以帮助我。只要告诉我你是否需要进一步的信息。 (我只需要两个邻居。不需要等等。)

编辑:@Trevor不,对不起,我不能。我更清楚地改变了这个例子。

4 个答案:

答案 0 :(得分:1)

注意:正如各种评论所述,@mellamokb's answer比我的好。我会删除这个答案但是因为它被接受了所以我无法接受。

/* Next Page */
SELECT ID
    FROM YourTable
    WHERE VIEWS <= (SELECT VIEWS FROM YourTable WHERE ID = $CurrentPageId)
        AND ID < $CurrentPageId
    ORDER BY VIEWS DESC, ID DESC LIMIT 1

/* Previous Page */
SELECT ID
    FROM YourTable
    WHERE VIEWS >= (SELECT VIEWS FROM YourTable WHERE ID = $CurrentPageId)
        AND ID > $CurrentPageId
    ORDER BY VIEWS, ID LIMIT 1

答案 1 :(得分:1)

上一页:

  select ID as PreviousId
    from PageViews
   where Views > (select Views From PageViews Where ID = @Id)
      or (
             Views = (select Views From PageViews Where ID = @Id)
             and ID > @id
         )
order by Views ASC, ID DESC
   limit 1

下一页:

  select ID as PreviousId
    from PageViews
   where Views < (select Views From PageViews Where ID = @Id)
      or (
             Views = (select Views From PageViews Where ID = @Id)
             and ID < @id
         )
order by Views DESC, ID DESC
   limit 1

答案 2 :(得分:0)

三个问题:

SELECT @MyID:=ID,@MyViews:=Views FROM Table WHERE ID=2;

使用本地“视图”:

SELECT ID,Views FROM Table WHERE Views <= @MyViews AND ID != @MyID ORDER BY Views DESC LIMIT 1;
SELECT ID,Views FROM Table WHERE Views >= @MyViews AND ID != @MyID ORDER BY Views ASC LIMIT 1;

并且,请确保您有关于视图的索引。

答案 3 :(得分:0)

    /* Previous Page */
SELECT ID
    FROM YourTable
    WHERE VIEWS < $CurrentPageViews 
    ORDER BY VIEWS DESC LIMIT 1

/* Next Page */
SELECT ID
    FROM YourTable
    WHERE VIEWS > $CurrentPageViews
    ORDER BY VIEWS LIMIT 1