Question on mySQL.
I have a table with columns like below:
BasePrice, Discount, NetPrice
Now assume that the calculation of net price happens like below:
NetPrice = BasePrice - Discount
Now, I do not mind entering the BasePrice
and Discount
values into the column on my own, manually using phpMyadmin (that is, direct backend updation). Since the NetPrice
value involves calculation as shown above, I do not want to update the column value for each row in the table, but would prefer the database updating it automatically for me ( not that I am weak at math :)
).
Is there someway to have the database update the NetPrice
column value automatically? I know I can use php to get the other two column values, calculate and then update the NetPrice
value, again using php code, but would prefer the db doing it on its own without any php/server side scripting.
I use mySQL and phpMyadmin for dev.
Thanks.
In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.
The syntax to modify a column in a table in MySQL (using the ALTER TABLE statement) is: ALTER TABLE table_name MODIFY column_name column_definition [ FIRST | AFTER column_name ]; table_name. The name of the table to modify.
UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.
You could use a single query to update all table:
UPDATE your_table
SET NetPrice = BasePrice - Discount
or you can use a trigger to alter that column anytime a row is added.
Something like this:
CREATE TRIGGER onInsert BEFORE INSERT ON `your_table`
FOR EACH ROW
BEGIN
SET NEW.NetPrice = NEW.BasePrice - NEW.Discount;
END;
As an alternative to Marco's (+1) answer, for just an INSERT, the simplest approach might be to reference columns assigned previously in the statement. For example:
INSERT INTO t (BasePrice, Discount, NetPrice) VALUES (17.00, 2.50, BasePrice-Discount);
For that NetPrice column to calculated correctly, the BasePrice
and Discount
columns must appear in the insert before the expression that calculates NetPrice
. (The values assigned to each column is available later in the statement, after the column is assigned a value.)
If you always want to guarantee that NetPrice is kept "in sync" if either BasePrice or Discount is modified, then a BEFORE UPDATE
trigger will do that for you, so the combination of a BEFORE INSERT
and BEFORE UPDATE
trigger would be appropriate. (See the answer from Marco.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With