我需要在mySQL表中进行简单的数学运算。
我有桌子payment_tbl 有字段:正常,罚款,退款并试图添加已归档的正常+罚款+退款?
payment_tbl代码:
create table payment_tbl (
payment_id INT (10) PRIMARY KEY AUTO_INCREMENT,
payment_amount decimal (5,2) not null,
payment_date DATE not null,
normal decimal (5,2) not null,
penalty decimal (5,2) not null,
refund decimal (5,2) not null,
out decimal (5,2));
INSERT into payment_tbl (
payment_amount,
payment_date,
normal,
penalty,
refund)
values ('5.55', '2015-05-05', '5.55','0', '0');
所以我试图把这个列作为所有三笔付款的总和?
答案 0 :(得分:2)
以下是generated columns的文档:
CREATE TABLE payment_tbl(
payment_id INT (10) PRIMARY KEY AUTO_INCREMENT,
payment_amount decimal (5,2) not null,
payment_date DATE not null,
normal decimal (5,2) not null,
penalty decimal (5,2) not null,
refund decimal (5,2) not null,
`out` decimal (5,2) AS (normal+penalty+refund)
);
我将out
列的定义修改为其他3列的总和。你不需要触发器。
答案 1 :(得分:0)
您可以使用此查询来添加COLUMN。如果您使用PERSISTENT Query,您还可以在此COLUMN上添加INDEX。
ALTER TABLE payment_tbl
ADD COLUMN `out` DECIMAL(5,2) AS ( normal + penalty + refund) VIRTUAL;
ALTER TABLE payment_tbl
ADD COLUMN `outp` DECIMAL(5,2) AS ( normal + penalty + refund) PERSISTENT;