【问题标题】:How to add MySQL table column with a default value of another column of the existing row如何使用现有行的另一列的默认值添加 MySQL 表列
【发布时间】:2020-09-29 21:40:20
【问题描述】:

当前现有的表如下所示:

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。

【问题讨论】:

标签: mysql mysql-workbench


【解决方案1】:

不可能作为默认列。您可以编写触发器并执行此操作或在 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;

【讨论】:

    【解决方案2】:

    虚拟列:

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

    【讨论】:

    • 每个问题每人一个答案。在一个答案中给出选项很好
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-31
    • 2021-01-17
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2016-09-08
    相关资源
    最近更新 更多