这让我完全难过。从一组数字 - 对于这个例子1到20,我正在尝试做上一个和下一个链接,所以他们最终会这样:我将提供从头开始的数字。
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
你知道如何为这样的事做sql吗?
我试图在这个基础上建立,但没有运气:
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;
表格数据
"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"
所需的输出
我提供的数字= 10
prev | next
-------------
6 | 10
答案 0 :(得分:1)
以下是MySQL
解决方案:
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
是您指定的内容。
您可以在SQL Fiddle中查看其工作原理。随意更改其数据和测试,