3

我在 MySQL 中有一个自引用表

Posts
 postId
 FK_PostId
 idx

idx 值当前为 0,但我需要更新它们,以便每个 postId 每个 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

我似乎无法为此进行智能查询。谁能帮我吗?

4

2 回答 2

3

这似乎可以解决问题

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;

基于此处的解决方案: 查询以添加基于 GROUP BY 的增量字段

于 2013-03-07T16:01:07.290 回答
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;
于 2013-03-07T15:51:38.307 回答