PHP/MYSQL Query: Get line above and below result!
I somehow need a way for the following:
User is located at some blog page Now I want to give him the ability to move either:
To the next more popular page OR to the next less popular page. Means, something like this:
[PAGE 5] | [PAGE 3 (User is here)] | [PAGE 2]
(Where Page 1 = most popular, Page 3 = least popular). My MySQL Table looks like this:
[ID] [VIEWS]
[1] [1000]
[2] [2560]
[3] [3200]
[4] [200]
[5] [4000]
My problem is the specific query. The only given variable is the ID: 2 in this case. Maybe you can help me out. Just tell me if you need further informations. (I only need the two neighbours. Page 4 etc. would not be needed.)
Edit: @Trevor No, sorry I cant. I ch开发者_运维问答anged the example so its more clearly.
NOTE: As worked out in the various comments, @mellamokb's answer is better than mine. I would delete this answer but am unable to since it was accepted.
/* 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
For previous page:
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
For next page:
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
or
/* 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
Three queries:
SELECT @MyID:=ID,@MyViews:=Views FROM Table WHERE ID=2;
Using local "Views":
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;
And, make sure you have an index on Views.
精彩评论