0

这是我的桌子:问题

id   | name
-----+-----
 2   | name 1
 3   | name 2 
 4   | name 3
 5   | name 4
 10  | name 5 
 20  | name 6
 21  | name 7

我有一个 id 说 5,我需要获取上一行和下一行,所以如果 id 为 5,我需要获取 4、5 和 10

现在我正在使用这些查询

select * from question where id = (select max(id) from question where id < 5);
select * from question where id = (select min(id) from question where id > 5);

我正在寻找的是单个查询(如果可能的话)。就像是

SELECT xx AS prevId, id, yy AS nextId FROM questions WHERE .......

如果没有前一个 id 或下一个 id 它应该是 0 或 -1

For example
id: 5
Return : 4, 5, 10

id:2
Return : -1, 2, 3

id: 21
Return 20, 21, -1

我知道如何通过多个查询和ifPHP 中的某些条件来做到这一点,但如果可能的话,我正在寻找一种纯 mySQL 方法。

4

2 回答 2

1

这里有几个例子,其他人可以判断哪个更有效。

查询 1

Select
  (select id from question where id<5 order by id desc limit 0,1) as prevId,
  id,
  (select id from question where id>5 order by id asc limit 0,1) as nextId
From question
Where id=5;

查询 2

Select
  (select max(id) from question where id<5) as prevId,
  id,
  (select min(id) from question where id>5) as nextId
From question 
Where id=5;

啊,没有看到-1的定义,需要更多的黑客攻击。Coalesce 函数接受 1..n 个参数并返回第一个非空值。

查询 3

Select
  Coalesce( (select max(id) from question where id<21), -1) as prevId,
  id,
  Coalesce( (select min(id) from question where id>21), -1) as nextId
From question
Where id=21;
于 2013-07-07T08:27:35.827 回答
0

对于下一条记录(ID):

SELECT * FROM `table_name` WHERE ID > $id ORDER BY ID LIMIT 1;

对于上一个记录(ID):

SELECT * FROM `table_name` WHERE ID < $id ORDER BY ID LIMIT 1;

$id是 php 中的一个变量,它会根据您的需要而变化

于 2013-07-07T07:58:41.540 回答