2013-03-07 66 views
1

分組遞增的值更新表我有一個自我引用表在MySQL

Posts 
postId 
FK_PostId 
idx 

的IDX值目前0,但我需要更新他們讓每一個有帖子ID每FK_PostId的遞增值。簡單地說,但非功能寫成

update idx = idx + 1 where FK_PostId is not null order by postId group by FK_PostID 

期望的結果

postId 15 FK_PostId 4 idx 0 
postId 16 FK_PostId 4 idx 1 
postId 17 FK_PostId 4 idx 2 
postId 18 FK_PostId 4 idx 3 
postId 24 FK_PostId 4 idx 4 
postId 32 FK_PostId 50 idx 0 
postId 35 FK_PostId 50 idx 1 

我似乎無法扎堆智能查詢此。 任何人都可以幫我嗎?

+0

請張貼以前的數據,以便我們能夠看到你'的頻15/4/0 ...' – fedorqui 2013-03-07 15:48:20

回答

2

這似乎這樣的伎倆

UPDATE WallPost p, 

( SELECT @r:= IF(@u = FK_PostID, @r + 1,0) AS ROWNUM, 
       postID, 
       FK_PostID, 
       @u:= FK_postID 
     FROM WallPost, 
       (SELECT @i:= 1) AS r, 
       (SELECT @u:= 0) AS u 
     WHERE FK_PostID is not null 
     ORDER BY FK_PostID, idx, postID 
    ) AS s 
set p.idx = s.ROWNUM 
where p.postId = s.postId; 

基於位置的解決方案: query to add incremental field based on GROUP BY

0
mysql> set @f := null; 
mysql> UPDATE Posts 
    SET 
     idx = IF(FK_postId = @f, @i := @i+1, @i := 1), 
     FK_postId = (@f := FK_postId) 
    ORDER BY FK_postId, postId; 
+1

你忘了也聲明'@ i'變量:'SET @f:= null,@i = null;' – Dwelle 2014-06-15 12:50:34

+0

@Dwellee,你不需要初始化'@ i',因爲邏輯保證在遞增之前,'@ i'會初始設置爲1。初始狀態「@ f」爲空保證它在第一次迭代時不會等於FK_postId,因此IF()函數的「else」表達式將設置爲「@ i」。 – 2014-06-15 16:57:00

+0

我真的不知道MySQL如何處理變量,但它似乎只在'FK_postId!= @ f'時返回'$ i = 1',在其他情況下它會嘗試增加未聲明的'$ i'並返回null ' - 從這個[SQLFiddle](http://sqlfiddle.com/#!2/6b27c/1) – Dwelle 2014-06-15 22:03:00