2013-07-08 35 views
0

我正在修復我們的(論壇)數據庫,因爲似乎某些線程中的多個帖子顯示爲相同的帖子編號(#2)。看來他們在各自的論壇主題中都佔有「1」的位置。更新MySQL中相關列的列中的增量值

我設法找到一個查詢,將通過下面的查詢設置這些位置值,以正確的數量:

select @i := -1; update `xf_post` set position = (select @i := @i + 1) where thread_id=1; 

不幸的是,我只通過MySQL命令行這樣做更新查詢我不斷選擇向上箭頭鍵,將'thread_id'值增加1,然後按下Return鍵。有沒有更快的方式通過循環或光標來做到這一點?我對SQL語法的其他部分並不是很熟悉,我只是基本瞭解。

回答

0

您可以使用下面的查詢,以獲得您想要爲每個線程的數字:

select thread_id, 
     (case when @prev = thread_id then @rn := 1 else @rn := @rn + 1 end) as rn, 
     @prev = @threadid 
from xf_post p cross join 
    (select @rn := 0, @thread_id = -1) const 
order by thread_id, position 

您可以測試了這一點,以確保它產生正確的價值觀。接下來你可以用joinupdate

update xf_post join 
     (select thread_id, post_id, 
       (case when @prev = thread_id then @rn := 1 else @rn := @rn + 1 end) as rn, 
       @prev = @threadid 
     from xf_post p cross join 
      (select @rn := 0, @thread_id = -1) const 
     order by thread_id, post_id 
     ) toupdate 
     on xf_post.post_id = toupdate.post_id 
    set xf_post.position = toupdate.rn;