问题
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