这是我的表:问题
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
我知道如何在PHP中使用多个查询和一些if
条件来执行此操作,但如果可能的话,我正在寻找纯粹的mySQL方法。
答案 0 :(得分: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;
答案 1 :(得分:0)
对于下一个记录(ID):
SELECT * FROM `table_name` WHERE ID > $id ORDER BY ID LIMIT 1;
对于prev记录(ID):
SELECT * FROM `table_name` WHERE ID < $id ORDER BY ID LIMIT 1;
这里$id
是php中的一个变量,根据你的愿望而变化