Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update table with incremented value grouped by column

Tags:

mysql

I have a self referencing table in MySQL

Posts
 postId
 FK_PostId
 idx

The idx values are currently 0 but I need to update them so that every postId has an incremented value per FK_PostId. Simply, but non-functionally written as

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

Desired result

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

I can't seem to get a smart query together for this. Can anyone help me out?

like image 820
Marc Avatar asked Aug 25 '26 18:08

Marc


1 Answers

This seems to do the trick

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;

Based on a solution here: query to add incremental field based on GROUP BY

like image 118
Marc Avatar answered Aug 28 '26 09:08

Marc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!