我在数据库中有这些数据:
ID col1 col2
32 2 0
31 2 0
76 1 0
12 0 0
10 0 0
25 0 1
20 0 1
28 0 2
这些数据已从此查询中获得:
SELECT ID, col1, col2
FROM tableA
ORDER BY col1 DESC, col2 ASC, ID DESC
一旦我有了 ID/col1 值,我想获取此查询的下一行。 是否可以通过唯一的查询来完成?
重要信息:col1 和 col2 不能同时不为零。如果 col1 不为零,则 col2 为零,反之亦然。
编辑: 我正在使用MySQL。没有API
假设我的 ID 为 31。那么我需要获取 ID 为 76 的行
如果我的 ID 为 10,那么我需要 ID 为 25 的行。
最佳答案
这是一种方法,尽管我确实想知道是否有更简单的方法:
select a.*
from TableA a cross jooin
(select a.*
from TableA a
where id = 31
) thea
where thea.col1 < a.col1 or
thea.col1 = a.col1 and thea.col2 > a.col2 or
thea.col1 = a.col1 and thea.col2 = a.col2 and thea.id < a.id
order by a.col1 DESC, a.col2 ASC, a.ID DESC
limit 1;
EDTI:
更简单的方法是使用变量:
select a.*
from (select a.*,
(@rn := if(a.id = 31,
if(@found := 1, 1, 1),
if(@found = 1, @rn + 1, -1)
)
) as rn
from tablea a cross join
(select @rn := 0, @found := 0) params
order by a.col1 DESC, a.col2 ASC, a.ID DESC
) a
where rn = 2;
关于mysql - 从查询中获取下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33323527/