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

q9rjltbz  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(486)

当前的现有表如下所示:

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工作台gui。

mrwjdhj3

mrwjdhj31#

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

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

或者可以创建虚拟列:

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

bd1hkmkf2#

虚拟列:

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

相关问题