简体   繁体   中英

Rails 5 MySQL: Table column as sum of two other columns

I wonder if anyone can help with a db question. I am using Rails 5 and MySQL;

I want to create a table where there are 3 integer columns. Columns 1 and 2 are populated by the user and column 3 is the result of c1xc2 and should stored as an integer. How would I go about creating such a table? I can happily create the tables without that last calculated column, just not sure the best way to go about it.

I did consider that maybe I don't need the final column at all, but rather each time the calculation was needed I could render the results using erb referring to c1 and c2

What are the benefits if any to storing the product in the table/

Many thanks.

What are the benefits if any to storing the product in the table

If you don't have anything specific to tell on that subject ("benefits") - there's rather none.

I did consider that maybe I don't need the final column at all, but rather each time the calculation was needed I could render the results using erb referring to c1 and c2

Exactly, you don't. In

SELECT col1, col2, (col1 + col2) AS col3 FROM yourtable WHERE col1 = <something>;

the sum costs nothing comparing to record lookup/fetch (unlike proposed trigger solution).

You can user triggers . Like before update .

Set New.SumValue = New.ValueOne + New.ValueTwo

But be careful so one of the columns can be NULL. So you will have to use IFNULL here .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM