Is it possible to create a column within a MySQL structure that automatically sums two other columns?
So if I have a table called TABLE:
Column A, Column B, and Column C.
I would want Column C to automatically sum Column A and Column B.
Is that possible?
If A changes, C changes.
If it possible than how.any example if you have.
You can achieve this with a VIEW:
CREATE TABLE table1 (a INT, b INT);
CREATE
OR replace VIEW V_TABLE AS
SELECT a, b, a + b AS c
FROM table1;
sqlfiddle
With a trigger:
DELIMITER $$
CREATE TRIGGER myTableAutoSum
BEFORE INSERT ON `myTable` FOR EACH ROW
BEGIN
SET NEW.ColumnC = NEW.ColumnA + NEW.ColumnB;
END;
$$
DELIMITER ;
Then this query:
INSERT INTO myTable (ColumnA, ColumnB) values(1, 1), (2, 3), (1, 4);
Will result in rows:
ColumnA ColumnB ColumnC
1 1 2
2 3 5
1 4 5
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