如何使用现有行的另一列的默认值添加 MySQL 表列

Roe*_*oel 4 mysql mysql-workbench

当前现有的表如下所示:

id    number    amount    
1     123       30000.00
2     123       15000.00
3     321       45000.00
...   ...       ...
1000  567       75000.00
Run Code Online (Sandbox Code Playgroud)

现在我想在每个现有行中添加allocated_amount具有默认值的新列amount

id    number    amount      allocated_amount  
1     123       30000.00    30000.00
2     123       15000.00    15000.00
3     321       45000.00    45000.00
...   ...       ...         ...
1000  567       75000.00    75000.00
Run Code Online (Sandbox Code Playgroud)

有可能的?我使用 MySQL Workbench GUI。

小智 6

不能作为默认列。您可以编写触发器并执行此操作或在 Mysql 5.7 中添加虚拟列。

或者

alter table Tab1 add allocated_amount int;  -- Add column
update Tab1 set allocated_amount= amount;   -- Set the value
Run Code Online (Sandbox Code Playgroud)

或者您可以创建一个虚拟列:

alter table Table1 
add allocated_amount integer GENERATED ALWAYS AS (amount) VIRTUAL;
Run Code Online (Sandbox Code Playgroud)