I am trying to update a column with help of previously updated column in phpMyAdmin. I am trying to calculate ratio by dividing advance by dep (ratio=advance/dep). I have this table :
#id# #dep# #cash# #advance# #ratio#
----------------------------------------
1 100 100 200 0
----------------------------------------
2 200 300 500 0
----------------------------------------
I am trying this code :
Update 'table1' Set 'ratio'= 'advance'/'dep';
I expect output to be 200/100 = 2 updated in ratio when i update value of columns dep or advance in table.
You can use a CREATE TRIGGER
on the table to calculate and set the new ratio of the affected rows:
CREATE TRIGGER upd_ratio BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN
SET NEW.ratio = NEW.advance / NEW.dep;
END
To UPDATE
and recalculate all records you can use the following UPDATE
statement. You should execute this once after creating the trigger to initialize the ratio
column.
UPDATE `table_name` SET `ratio` = `advance` / `dep`
You can also use a CREATE VIEW
to create a view of the table (without the ratio
column). You can dynamically calculate the ratio
column and don't need to store and recalculate the value after UPDATE
:
CREATE VIEW view_name AS SELECT *, advance / dep AS ratio FROM table_name;
Note: As @P.Salmon also mentioned in the comments you need to use backticks instead of single-quotes. You current UPDATE
statement isn't valid.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.