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
我想更新表格
答案 0 :(得分: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;