【问题标题】:Update statement to update two columns of a table using the next value of a column in same table使用同一表中列的下一个值更新表的两列的更新语句
【发布时间】:2019-05-23 15:11:14
【问题描述】:

我有一个表,我想在其中更新两列。下面是例子:

实际表格:

Team    | PLAYERNUM|  NAME 
--------+----------+--------
A       |    1     |   ONE  | 
A       |    2     |   TWO  | 
A       |    3     |   THREE| 
B       |    1     |   FOUR | 
B       |    2     |   FIVE | 
B       |    3     |   SIX  |

预期结果:

Team    |PLAYERNUM |  NAME 
--------+----------+--------
A       |    1     |   ONE  | 
A       |    2     |   TWO  | 
A       |    3     |   THREE| 
A       |    4     |   FOUR | 
A       |    5     |   FIVE | 
A       |    6     |   SIX  |

在“Team”和“PLAYERNUM”列上启用了唯一约束。现在,我想将 Team 为“B”的所有行更新为“A”。我收到一个唯一违反约束的错误,因为“PLAYERNUM”是唯一的。关于如何将 Team B 和 PLAYERNUM 更新为 4 5 6 的任何线索。

【问题讨论】:

    标签: sql oracle sql-update unique-constraint


    【解决方案1】:

    您可以使用common-table-expressionrow_number()窗口解析功能进行更新操作:

    update tab t
       set playernum = (
      with cte as (
        select t.*, row_number() over (order by Team,playernum) as rn
        from tab t 
      )
      select rn
        from  cte 
       where cte.team = t.team and cte.playernum = t.playernum
     ), team = 'A';
    

    Demo

    如果仅将列 team 更新为 team = 'A',则会出现主键约束冲突错误(在演示中尝试),但上述样式不会产生错误。 p>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-11
      • 1970-01-01
      • 2020-09-09
      • 1970-01-01
      • 1970-01-01
      • 2021-10-16
      • 1970-01-01
      相关资源
      最近更新 更多