2013-07-07 74 views
0

這是我的表:問題合併多個MySQL查詢來獲得結果作爲單列

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應該是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方法。

回答

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的定義,需要更多的一些黑客。合併函數需要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; 
+0

工程就像一個魅力:) – phpsessionid

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中,其變化根據你的願望

+0

這與我有什麼在我的問題。我正在尋找別的東西。 Plz檢查問題。 – phpsessionid