选择提供的ID之前和之后的第5条记录以及其他条件

时间:2013-09-25 05:26:57

标签: mysql sql

我正在尝试从包含下面数据的表中提供的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"

2 个答案:

答案 0 :(得分:8)

尝试使用UNION ALL两个LIMIT为6的查询,因为<=而第二个

获取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

See that fiddle for 5 records before after 10

在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

See that fiddle for 5th record before and after 10

显示行记录

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`

Display 5th record before and after 10 row wise

此解决方案并非仅针对第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 

答案 1 :(得分: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 ;