Mysql更新自我联接,基于组

时间:2019-03-05 07:34:34

标签: mysql sql sql-update auto-increment

我有一个表,其结构与下面类似。

+ ---- + --------------- + ------- +
| id |组|值|
+ ---- + --------------- + ------- +
| 1 | g1 |空|
| 2 | g1 |空|
| 3 | g2 |空|
| 4 | g2 |空|
| 5 | g2 |空|
| 6 | g3 |空|
| 7 | g3 |空|
| 8 | g4 |空|
| 9 | g4 |空|
+ ---- + --------------- + ------- +

我需要更新value列,以使表看起来像

+ ---- + --------------- + ------- +
| id |组|值|
+ ---- + --------------- + ------- +
| 1 | g1 | 1 |
| 2 | g1 | 2 |
| 3 | g2 | 1 |
| 4 | g2 | 2 |
| 5 | g2 | 3 |
| 6 | g3 | 1 |
| 7 | g3 | 2 |
| 8 | g4 | 1 |
| 9 | g4 | 2 |
+ ---- + --------------- + ------- +

基本上,我是基于value列来增加group列。

3 个答案:

答案 0 :(得分:0)

您可以在下面尝试-使用自我加入

DEMO

update tablename t
join
(select b.id,b.groupname,count(b.id) as val from t1 a
join t1 b on a.groupname=b.groupname
and a.id<=b.id
group by b.id,b.groupname
)d on t.id=d.id
set value=val

OR

如果您的mysql版本是8.0+,则可以使用row_number()函数

update tablename t
join
(
  select *, row_number() over(partition by groupname order by id) as rn from t1 
)d on t.id=d.id
set value=rn

答案 1 :(得分:0)

请尝试这个,希望对您有用

Update A 
set value = _val
from @tblName As A
INNER JOIN (
SELECT id,Row_NUMBER() over(partition by [group] order by id) as _val  from  @tblName
)As B ON A.id = B.id

答案 2 :(得分:0)

在旧版本的MySQL中,变量是最简单的方法:

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

update t
    set value = (@rn := if(@grp = t.group, @rn + 1,
                           if(@grp := t.group, 1, 1)
                          )
                )
    order by group, id;

在MySQL 8.0中,使用fa06的第二个查询。