Insert new row with data computed from other rows

前端 未结 2 1403
忘掉有多难
忘掉有多难 2021-01-19 01:07

Suppose I have a MySQL table called MyTable, that looks like this:

+----+------+-------+
| Id | Type | Value |
+----+------+-------+
|  0 | A    |     1 |
|          


        
相关标签:
2条回答
  • 2021-01-19 01:43

    Just add the following line before your select statement:

    INSERT MyTable (Id, Type, Value)
    
    0 讨论(0)
  • 2021-01-19 01:46

    You can just append that select (slightly modified as in "you don't need the as clauses") onto an insert. For example:

    insert into MyTable (Id,Type,Value)
        select MyTable_A.Id, 'C', (A_Val + B_Val) from ...
    

    assuming that your query is actually correct - I make no evaluation of that :-)

    By way of further example,

    insert into MyTable (Id,Type,Value)
        select Id+1000, 'C', Value from MyTable where Type = 'A'
    

    would add the following rows:

    +------+------+-------+
    | Id   | Type | Value |
    +------+------+-------+
    | 1000 | C    |     1 |
    | 1001 | C    |     2 |
    | 1002 | C    |     5 |
    +------+------+-------+
    
    0 讨论(0)
提交回复
热议问题