Sum total of several MySQL columns stored in another column?

前端 未结 4 887
独厮守ぢ
独厮守ぢ 2021-01-20 13:27

I have several columns in a MySQL database that I would like to add and store in another column:

column1     column2     column3    subtotal
10          10           


        
相关标签:
4条回答
  • 2021-01-20 13:52
    update yourtable set subtotal = col1 + col2 + col3
    
    0 讨论(0)
  • 2021-01-20 13:53

    Well if this is just a one time deal you could do an update query like so:

    UPDATE MyTable set subtotal = (column1 + column2 + column3)
    

    If you want it to be calculated on insert, you could have a calculated column.

    I would personally just wait until you need it to calculate it so that information that could easily be derived from your data isn't bloating your DB.

    0 讨论(0)
  • 2021-01-20 13:58

    How about this?

    UPDATE tableName SET subtotal = (column1 + column2 + column3)
    

    Update 1

    If you really don't need subtotal column in table just use query as

    SELECT *, (column1 + column2 + column3) as subtotal
    FROM tableName
    

    Demo

    0 讨论(0)
  • 2021-01-20 14:11

    If you simply update subtotal, you have to maintain its value - ie every time one of the other columns is updated, your code has to remember to update subtotal too.

    There are two ways to address this issue:

    1. Create a trigger that fires when the row is updated. This option requires database "kung fu" and isn't immediately obvious to anyone else looking at the table the the trigger exists
    2. Create a VIEW that does the calculation

    I think option 2 is the best approach.

    Here's how you code a view.

    create view mytable_totalled as
    select col1, col2, col3,  col1 + col2 + col3 as subtotal
    from mytable
    

    Once created, the view can be used just like a table (with a few caveats), but you can certainly do any kind of select on it. The new column is calculated on the fly when selected

    0 讨论(0)
提交回复
热议问题