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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6805498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:35:36  来源:igfitidea点击:

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

mysqlcreate-table

提问by riyana

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

是否可以在 mysql 中创建一个包含两个列值的列的表?像这样:

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

回答by TehShrike

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 子句中引用组合数据。

回答by Edgar Velasquez Lim

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:

您可以在表上创建一个触发器,以便每次在 test1 表上发生 INSERT 时,MySQL 都会计算并自动插入该列值。制作表格:

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 触发器。

回答by shabbychef

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 上对我有用。

回答by Seb

Little fix :

小修复:

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