Thingamajig
Thingamajig

Reputation: 4465

MySQL: sum of two columns

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.

Upvotes: 1

Views: 13249

Answers (2)

John Woo
John Woo

Reputation: 263893

The best way to do is to calculate the records in your application level before inserting it on the database.

Upvotes: 3

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174457

It is possible with a View or a trigger. The View is the better solution in most cases.

View:

Your table TABLE would have only the columns A and B.
The view would then look something like this:

create or replace view V_TABLE as
select A, B, A + B as C
from TABLE;

If you need to query TABLE you use the view instead of the table itself. Each query will than return the correct C.

Trigger:

Your table TABLE would have all three columns A, B and C.
You would create a trigger on A and on B that update C as soon as A or B changes.

This answer assumes that in your case it is not feasible to calculate the value directly in your application.

Upvotes: 5

Related Questions