8

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

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

或像这样:

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

4 回答 4

15

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.

于 2011-07-24T07:35:24.313 回答
6

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.

于 2011-07-24T07:37:24.343 回答
4

我也有这个问题。从 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;

这适用于我在 MySQL 5.6.22 上。

于 2015-02-26T20:43:08.610 回答
0

小修复:

CREATE TRIGGER triggername BEFORE INSERT
ON test1
FOR EACH ROW
SET NEW.number3=NEW.number1+NEW.number2
于 2013-05-27T11:33:11.163 回答