0

This has me completely stumped. From a set of numbers - for this example 1 to 20, I'm trying to do previous and next links, so they end up like this: I'll be supplying the number to start from.

1       6           11          16
2       7           12          17
3       8           13          18
4       9           14          19
5       10          15          20
n-5    p-6 n-10   p-11 n-15    p-16

Have you any idea how to do the sql for something like this?

I was trying to build on this one, but no luck:

SELECT c.id,
  (SELECT MAX(p.id) FROM mytable p WHERE p.id < c.id AND p.country = 'us') prev_id,
  (SELECT MIN(n.id) FROM mytable n WHERE n.id > c.id AND n.country = 'us') next_id
FROM mytable as c WHERE c.id = 5;

Table data

    "id"    "country"
"1"     "US"
"2"     "US"
"3"     "US"
"4"     "US"
"5"     "US"
"6"     "US"
"7"     "US"
"8"     "US"
"9"     "US"
"10"    "US"
"11"    "US"
"12"    "US"

Desired output

number provided by me = 10

prev  | next
-------------
6     | 10
10
  • 1
    Post the schema (field structure) of MyTable. Commented Sep 22, 2013 at 18:14
  • It's simple. I posted it. I'm using this for testing. Commented Sep 22, 2013 at 18:18
  • And what is the requirement. To print IDs in 4 columns? Commented Sep 22, 2013 at 18:30
  • Not 4 columns. One one column. If I gave you No. 10, the previous would be 6 and next would be 10. See p-6 n-10 in my example. Commented Sep 22, 2013 at 18:35
  • Can you please provide the desired output based on your sample data (you already posted)? Commented Sep 22, 2013 at 18:44

1 Answer 1

1

Here is MySQL solution:

SET @number=15;
SET @counter=0;


SELECT x.id, @number as next
FROM (
SELECT id, (@counter:=@counter+1) as line FROM TableData WHERE id <=@number ORDER BY id 
) x
WHERE x.line = @counter-5;

number is what you specify.

You can see how it works in SQL Fiddle. Feel free to change its data and test,

Sign up to request clarification or add additional context in comments.

4 Comments

Right. Thanks a lot for this. I tested here and it seems to be working nicely.
Link now works. I added 'CA' (not 'US') record and removed some lines so IDs are not sequential.
Your solution works fantastic. Thanks very much for helping on this. BTW, is that really you in your avatar image?
No, it's not me. Got this image from internet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.