Is it possible to create a column in MySQL with an expression as a default value?

点点圈 提交于 2021-02-17 03:20:23

问题


How would one implement this in MySQL:

CREATE TABLE employee (
  employeemonthly DECIMAL(10,2), 
  employeeyearly DECIMAL(10,2) DEFAULT employeemonthly*12
);

回答1:


use a insert trigger for that. Something like this

DELIMITER |

CREATE TRIGGER default_yearly BEFORE INSERT ON employee
  FOR EACH ROW BEGIN   
    SET NEW.employeeyearly = NEW.employeemonthly * 12;
  END;
|

DELIMITER ;



回答2:


I would use a view:

CREATE VIEW vemployees AS
  SELECT e.employeemonthly,
         e.employeemonthly * 12 AS employeeyearly
    FROM EMPLOYEE e

...because there's little need to dedicate storage space for an easily calculated value. Otherwise, use a function or simply write the expression into whatever query/stored procedure you need.

What really depends is:

  • How often you need to access this data
  • How complex the operation is to get the result you need

I recommend starting with not storing the value. If performance gets to be a problem, then dedicate a column for the values storage -- not before. At that, a trigger is a bit overkill to me, when you can use (psuedocode):

INSERT INTO employee 
  (...employeemonthly, employeeyearly, ...)
VALUES
  (...@employeemonthly, @employeemonthly * 12, ...



回答3:


Use a trigger for the insert event, access the new record data using NEW and set the appropiate values.



来源:https://stackoverflow.com/questions/10863263/is-it-possible-to-create-a-column-in-mysql-with-an-expression-as-a-default-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!