我在 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

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

最佳答案

这似乎可以解决问题

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

关于mysql - 使用按列分组的递增值更新表,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15275469/

10-16 15:04