mysql - 使用按列分组的增量值更新表

标签 mysql

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

相关文章:

php - 为 Beta 应用程序推荐错误跟踪软件

php - while循环没有输出正确的结果

mysql - Postgres 使用 btree 索引 vs MySQL B+trees

mysql - 为什么长时间运行的选择查询会导致 MySQL 从属数据库中的复制滞后?

php - 如何在mysql中使用oop从mysql读取数据?

php - Artisan Migrate 被机器拒绝

mysql - 消除 PostgreSQL SELECT 语句中的重复行

php - 函数不知从哪里输出数组 0 个元素

javascript - 如何在 node.js 中执行同步 SQL 查询

mysql - WHERE 子句中的一些错误