gpt4 book ai didi

mysql - 更新 MySQL 中相关列的列中的增量值

转载 作者:行者123 更新时间:2023-11-30 01:30:32 27 4
gpt4 key购买 nike

我正在修复我们的(论坛)数据库,因为某些线程中的多个帖子似乎显示了相同的帖子编号(#2)。似乎他们在每个论坛线程中都占据“1”的位置。

我设法找到一个查询,通过下面的查询将这些位置值设置为正确的数字:

select @i := -1; update `xf_post` set position = (select @i := @i + 1) where thread_id=1; 

不幸的是,我只通过 MySQL 命令行执行此更新查询,其中我不断选择向上箭头键,将“thread_id”值增加 1,然后按 Return 键。有没有更快的方法通过循环或游标来做到这一点?我对 SQL 语法的其他部分不是很熟悉,只能了解基础知识。

最佳答案

您可以使用以下查询来获取每个线程所需的数字:

select thread_id,
(case when @prev = thread_id then @rn := 1 else @rn := @rn + 1 end) as rn,
@prev = @threadid
from xf_post p cross join
(select @rn := 0, @thread_id = -1) const
order by thread_id, position

您可以对其进行测试以确保它产生正确的值。接下来,您可以使用 join 进行更新:

update xf_post join
(select thread_id, post_id,
(case when @prev = thread_id then @rn := 1 else @rn := @rn + 1 end) as rn,
@prev = @threadid
from xf_post p cross join
(select @rn := 0, @thread_id = -1) const
order by thread_id, post_id
) toupdate
on xf_post.post_id = toupdate.post_id
set xf_post.position = toupdate.rn;

关于mysql - 更新 MySQL 中相关列的列中的增量值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17524567/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com