我在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
我似乎无法为此获得智能查询。 任何人都可以帮助我吗?
答案 0 :(得分: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;
答案 1 :(得分: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;