如何在现有行中添加MySQL表列,并将默认值设置为另一列的值

6

当前的现有表格如下:

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
这可能会有所帮助,但他们谈论使用触发器的方式:https://dev59.com/JGw15IYBdhLWcg3w0fEV。用于确定分配金额的规则是什么? - J.D. Pace
那是真的,谢谢你 - Shift 'n Tab
2个回答

10

默认情况下无法实现此列。您可以编写触发器来完成此操作,或在Mysql 5.7中添加虚拟列。

或者

alter table Tab1 add allocated_amount int;  -- Add column
update Tab1 set allocated_amount= amount;   -- Set the value

你可以创建一个虚拟列(Virtual Column):
alter table Table1 
add allocated_amount integer GENERATED ALWAYS AS (amount) VIRTUAL;

-1

虚拟列:

alter table Table1 
add allocated_amount integer GENERATED ALWAYS AS (amount) VIRTUAL;

4
每个问题请只回答一个答案。在单个答案中提供多个选项也可以。 - RiggsFolly
让我们删除这个答案,以免让新手感到困惑,请;-) - jave.web

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接