简体   繁体   中英

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

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`
);

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.

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.

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.

Little fix :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM