2011-07-28 31 views
0

mysql fetch previous or next record order by anyother field name and not by using order by id如何下/上一紀錄在MySQL

select * from table where id > $id order by name asc limit 1 
select * from table where id < $id order by name desc limit 1 

我能夠獲得下一個和以前的記錄,但在這種情況下,我怎樣才能 下一個和以前的記錄更新升級。

ID Links   orderID 
14 Google.com  1 
15 Yahoo.com  2 
20 gmail.com  3 
25 facebook.com 4 

關於什麼的,如果我用+和 - 在前面的按鈕各個環節的升級和降級它們,然後重新排列由單編號菜單命令?

+0

使用您已知的那些查詢來檢索要更新的行的ID,使用您剛剛檢索到的兩個ID發出兩個具有WHERE ID = X'的UPDATE查詢。哪部分是問題? –

回答

0

絕對不需要做這兩個選擇。 你可以做到以下幾點:

UPDATE表SET字段= '某個值' WHERE ID = $ ID + 1

UPDATE表SET字段= '某個值' WHERE ID = $ ID-1

你去那裏:)

+2

假定連續的ID,這是**非常**限制條件。 – Naltharial

1

好吧,如果你真的想這樣做,在一個單一的查詢,您可以使用子查詢,找出需要更新的ID。問題在於,由於明顯的數據完整性原因,MySQL無法更新您嘗試子查詢的同一個表。所以你需要使用一些解決方法,比如在子查詢中創建一個臨時表。

UPDATE table AS t 
SET [...] 
WHERE t.`id` = (select * FROM (select `id` from table where `id` > $id order by `id` asc limit 1) AS sq)