1
id    data1        data2       
1      10          15           
2      10          20     

I have this table, and I want to add new column (point) in this table.

id     data1      data2        point
1      100         105           5
2      100         200          100

I'd like to add this point value by calculating this formula as follows:

point = (data2 - data1)/data1 * 100 

How can I add this value into point column?

Please let me know. Thanks

Taryn
  • 242,637
  • 56
  • 362
  • 405
Soo
  • 387
  • 2
  • 10
  • 19
  • 1
    Possible duplicate of [Column calculated from another column?](http://stackoverflow.com/questions/5222044/column-calculated-from-another-column) – Ed Gibbs May 23 '13 at 18:19

3 Answers3

2

Why not just use a VIEW

CREATE VIEW vw_Table1 AS
SELECT id, data1, data2, (data2 - data1)/data1 * 100 point
  FROM table1

SQLFiddle

peterm
  • 91,357
  • 15
  • 148
  • 157
1

You can use a trigger to keep it updated as @Yogendra Singh said, but if its a one-time thing then you can do it in a single UPDATE statement:

ALTER TABLE data ADD COLUMN point integer;
UPDATE data SET point = (data2 - data1)/data1 * 100;

The trigger function would look like:

CREATE TRIGGER update_point BEFORE INSERT ON data
  FOR EACH ROW BEGIN
    SET NEW.point = (data2 - data1)/data1 * 100;
  END;
Cody Caughlan
  • 32,456
  • 5
  • 63
  • 68
0

I think you can use a after insert/update trigger to update the point column after inserting/updating the values in the data1 and data2 columns.

You may want to refer Creating Triggers in MySQL for more details.

Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73