Create table in mysql with one column containing sum of another two columns value

谁说胖子不能爱 提交于 2019-12-28 22:27:23

问题


Is it possible in mysql to create a table with a column that combines two column values? something like this:

create table test1 (
    number1 int,
    number2 int,
    total int DEFAULT (number1+number2)
);

or like this :

CREATE TABLE `Result` (
    `aCount` INT DEFAULT 0,
    `bCount` INT DEFAULT 0,
    `cCount` =  `aCount` + `bCount`
);

回答1:


It is not possible to do that exactly, but you can create a view based on a query that combines them:

CREATE VIEW `my_wacky_view` AS
SELECT `number1`, `number2`, `number1` + `number2` AS `total`
FROM `test1`;

I would avoid actually storing the combined data in a table, unless you're going to be running lots of queries that will reference the combined data in their WHERE clauses.




回答2:


You can create a trigger on the table so MySQL calculates and automatically inserts that column value every time an INSERT happens on your test1 table. Make the table:

create table test1 (
    number1 int,
    number2 int,
    number3 int
);

Then create a Trigger

CREATE TRIGGER triggername AFTER INSERT
ON test1
FOR EACH ROW
UPDATE test1 SET NEW.number3=NEW.number1+NEW.number2

MySQL documentation on triggers: http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html

Make sure to add the ON UPDATE trigger as well if you expect UPDATES to happen to the rows.




回答3:


I had this issue as well. From Edgar Velasquez' answer here, and the answer to this question, I stumbled upon this incantation:

CREATE TRIGGER insert_t BEFORE INSERT
ON test1
FOR EACH ROW
SET NEW.number3=NEW.number1+NEW.number2;

CREATE TRIGGER insert_t_two BEFORE UPDATE
ON test1
FOR EACH ROW
SET NEW.number3=NEW.number1+NEW.number2;

This works for me on MySQL 5.6.22.




回答4:


Little fix :

CREATE TRIGGER triggername BEFORE INSERT
ON test1
FOR EACH ROW
SET NEW.number3=NEW.number1+NEW.number2


来源:https://stackoverflow.com/questions/6805498/create-table-in-mysql-with-one-column-containing-sum-of-another-two-columns-valu

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