在mysql中创建表,其中一列包含另外两列值的总和
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`
);
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`
);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不可能完全做到这一点,但您可以基于组合它们的查询创建一个视图:
我会避免实际将组合数据存储在表中,除非您要运行大量查询来引用在 WHERE 子句中组合数据。
It is not possible to do that exactly, but you can create a view based on a query that combines them:
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.
您可以在表上创建触发器,以便每次在 test1 表上发生 INSERT 时 MySQL 都会计算并自动插入该列值。建表:
然后创建一个触发器
关于触发器的MySQL文档:
http://dev.mysql.com/doc/refman/5.0 /en/create-trigger.html
如果您希望行发生更新,请确保添加 ON UPDATE 触发器。
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:
Then create a Trigger
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.
我也有这个问题。从埃德加·维拉斯奎兹(Edgar Velasquez)的回答以及这个问题的答案中,我偶然发现了这个咒语:
这对我的 MySQL 5.6.22 有效。
I had this issue as well. From Edgar Velasquez' answer here, and the answer to this question, I stumbled upon this incantation:
This works for me on MySQL 5.6.22.
小修复:
Little fix :