Create a column in Mysql that automatically divides the values into two other columns

2

I need to explain how I can make it similar to what happens in Excel I can create a column in Mysql that divides the values of the other two columns. Something like column 1 / column 2 = column 3.

For example I have two columns and several rows, in the first rows in column1 I would have the value 4, in the first row in column2 I would have the value 2, in the first row of column3 would be the value of 4/2

    
asked by anonymous 01.04.2015 / 20:18

2 answers

4

As of version 5.7 you can create columns calculated . The (simplified) syntax is as follows:

col_name data_type [GENERATED ALWAYS] AS (expression)

Applied to your case would look like this:

CREATE TABLE tabela (
   campo1 DOUBLE,
   campo2 DOUBLE,
   divisao DOUBLE AS (campo1/campo2)
);

If you use a previous version there are 3 possible solutions:

1 - Do the SELECT calculation:

In the indication of the columns that it should return, others that are calculated according to the columns of the table can be defined.

SELECT campo1, campo2, campo1/campo2 AS nomeQueQuiserDar FROM tabela

With the AS clause you can give the name you want to the calculated result.

See SQLFiddle

2 - Create a VIEW with the calculated field:

CREATE VIEW nome_view AS
SELECT campo1, campo2, campo1/campo2 AS divisao FROM tabela;

Use VIEW instead of the table in SELECT :

SELECT campo1, campo2, divisao FROM nome_view  

3 - Create a TRIGGER that calculates the result and saves it to a table column:

CREATE TRIGGER nome_trigger AFTER INSERT
ON tabela
FOR EACH ROW SET NEW.campo3 = NEW.campo1 / NEW.campo2

You have to create field3 in the table before you create the TRIGGER .

ALTER TABLE tabela ADD campo3 DOUBLE

If the table already has data, before creating the TRIGGER , update field3 based on existing data.

UPDATE tabela SET campo3 = campo1/campo2

If the values of field1 and field2 can be changed, you will need to create another TRIGGER to reflect this change in field3.

CREATE TRIGGER update_trigger BEFORE UPDATE
ON tabela
FOR EACH ROW SET NEW.campo3 = NEW.campo1 / NEW.campo2
    
01.04.2015 / 22:37
0

It would also be possible to create a calculated column, for example:

Create table ( campo1 double, campo2 double, campo3 as ((campo1/campo2) as double)); 

This type of table can interfere with processing so check another persisted table type ...

I hope I have helped.

    
24.11.2015 / 06:46