gpt4 book ai didi

mysql - 如何自动增加mysql中特定列的值

转载 作者:行者123 更新时间:2023-11-29 21:34:07 26 4
gpt4 key购买 nike

Table 1
id | uname | flag
1 | abc | 0
2 | abc | 0
3 | abc | 0
4 | bcd | 0
5 | bcd | 0
6 | cdf | 0
7 | ghi | 0
8 | ghi | 0

我想根据它们的 uname 出现情况增加标志值,从 0 开始

Table 1
id | uname | flag
1 | abc | 2
2 | abc | 1
3 | abc | 0
4 | bcd | 1
5 | bcd | 0
6 | cdf | 0
7 | ghi | 1
8 | ghi | 0

我想更新表格

最佳答案

您可以使用带有变量的UPDATE来修改表:

set @u := '';
set @rn := 0;

update table1
set flag = if(@u = uname, @rn := @rn + 1,
if(@u := uname, 1, 1)
)
order by uname, id desc;

不幸的是,当您使用 order by 时,MySQL 不允许您在更新中设置变量。如果您只需要一条语句,那么您可以使用 join:

update table1 t1 join
(select t1.*,
(@rn := if(@u = uname, @rn := @rn + 1,
if(@u := uname, 1, 1)
)
) as rn
from table1 t1 cross join
(select @rn := 0, @u := '') params
order by uname, id desc
) tt
on t1.id = tt.id
set t1.flag = tt.rn;

关于mysql - 如何自动增加mysql中特定列的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35036697/

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