Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate two columns they automatic put into total column

Tags:

sql

mysql

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.

like image 240
John Avatar asked Dec 09 '25 23:12

John


2 Answers

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

like image 88
Filipe Silva Avatar answered Dec 12 '25 11:12

Filipe Silva


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
like image 42
Jeroen Avatar answered Dec 12 '25 11:12

Jeroen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!