1

我正在尝试从具有如下数据的表中选择提供的 id 之前和之后的第 5 条记录。

我想到的是:select id-5, id+10 from devTable where id = 10 and stateCode = 'CA';

但是,考虑到 stateCode,这实际上并没有在提供的 id 之前和之后为您提供第 5 个 id,它似乎只是将 /sub 5 添加到提供的 id 中。你知道如何以正确的方式做到这一点吗?

期望的结果

supplied id = 10 and stateCode = CA
prev | next
2    | 16

supplied id = 9 and stateCode = NY
prev | next
NULL | NULL

数据

"id"  | "stateCode"
-------------------
"1"     "CA"
"2"     "CA"
"3"     "CA"
"4"     "CA"
"5"     "NY"
"6"     "NY"
"7"     "CA"
"8"     "CA"
"9"     "NY"
"10"    "CA"
"11"    "CA"
"12"    "NY"
"13"    "CA"
"14"    "CA"
"15"    "CA"
"16"    "CA"
4

2 回答 2

8

尝试使用UNION ALL两个查询,LIMIT其中一个为 6 <=,第二个为 5

获取 id= 10 前后的 5 条记录

(SELECT *  FROM devTable WHERE id <= 10 AND stateCode = 'CA' ORDER BY id DESC LIMIT 6)
UNION ALL
(SELECT *  FROM devTable WHERE id > 10 AND stateCode = 'CA' ORDER BY id ASC  LIMIT 5)
ORDER BY id

在 10 之前看到 5 条记录的小提琴

在 id= 10 之前和之后获得第 5 条记录

(SELECT *  FROM devTable WHERE id < 10 AND stateCode = 'CA' ORDER BY id DESC LIMIT 4,1)
UNION ALL
(SELECT *  FROM devTable WHERE id > 10 AND stateCode = 'CA' ORDER BY id ASC  LIMIT 4,1)
ORDER BY id

在 10 之前和之后看到第 5 条记录的小提琴

逐行显示记录

SELECT 
(SELECT id  FROM devTable WHERE id < 10 AND stateCode = 'CA' ORDER BY id DESC LIMIT 4,1) AS `prev`,
(SELECT id  FROM devTable WHERE id > 10 AND stateCode = 'CA' ORDER BY id ASC  LIMIT 4,1) AS `next`

在 10 行之前和之后显示第 5 条记录

此解决方案并非仅针对第 5 条记录,它也可用于第 n条记录

例子

(SELECT 
  * 
FROM
  devTable 
WHERE id < 10 
  AND stateCode = 'CA' 
ORDER BY id DESC 
LIMIT (n - 1), 1) 

UNION ALL 

(SELECT 
  * 
FROM
  devTable 
WHERE id > 10 
  AND stateCode = 'CA' 
ORDER BY id ASC 
LIMIT (n - 1), 1) 
ORDER BY id 
于 2013-09-25T05:43:16.163 回答
0

对于 Oracle,在给定 id 之前查询第 5 条记录

select * from (select id, statecode,rownum as rw 
from devTable where statecode = 'CA' and id < 10  
order by id desc) a
where a.rw = 5 ; 

在给定 id 后查询第 5 条记录

select * from (select id, statecode,rownum as rw 
from devTable where statecode = 'CA' and id > 10  
order by id asc) a
where a.rw = 5 ; 
于 2013-09-25T06:10:29.413 回答