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