简体   繁体   English

在mysql中创建表,其中一列包含另外两列的值的总和

[英]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? 是否有可能在mysql中创建一个包含两列值的列的表? 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. 我会避免实际将组合数据存储在表中,除非您将运行大量将在其WHERE子句中引用组合数据的查询。

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. 您可以在表上创建一个触发器,以便MySQL计算并在每次在test1表上发生INSERT时自动插入该列值。 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 关于触发器的MySQL文档: 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. 如果您希望行发生UPDATES,请确保添加ON UPDATE触发器。

I had this issue as well. 我也有这个问题。 From Edgar Velasquez' answer here, and the answer to this question , I stumbled upon this incantation: 从Edgar Velasquez在这里的回答,以及这个问题的答案,我偶然发现了这个咒语:

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. 这适用于MySQL 5.6.22。

Little fix : 小修复:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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