如何添加MySQL表列,其默认值为现有行的另一列

时间:2017-12-06 02:32:41

标签: mysql mysql-workbench

当前现有的表格如下所示:

id    number    amount    
1     123       30000.00
2     123       15000.00
3     321       45000.00
...   ...       ...
1000  567       75000.00

现在,我想添加新列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

有可能吗?我正在使用MySQL Workbench GUI。

2 个答案:

答案 0 :(得分:1)

无法作为默认列。您可以编写一个触发器并在Mysql 5.7中添加或添加虚拟列。

OR alter table Tab1 add allocated_amount int; - 添加列 更新Tab1 set allocated_amount = amount; - 设置值

答案 1 :(得分:0)

虚拟专栏: alter table Table1 add allocated_amount integer GENERATED ALWAYS AS(amount)VIRTUAL;