简体   繁体   English

两个字段的总和

[英]Sum of two fields

I have a mysql table with 2 fields: numPears (int) and numApples (int) and i'd like to have a numFruit (int) that automatically get these 2 values and sum them. 我有一个包含2个字段的mysql表: numPears (int)和numApples (int),我想有一个numFruit (int)自动获取这两个值并numFruit它们。 Is that possible? 那可能吗?

Example

So that if a query 所以,如果一个查询

INSERT INTO strange_table (fruitID, numPears, numApples) VALUES (1, 1, 5);

And then query 然后查询

SELECT numFruit FROM strange_table WHERE fruitID = 1;

It returns me 6 . 它让我回归6

If you are looking to create a static value every time a new row comes into the DB, use a trigger. 如果要在每次新行进入数据库时​​创建静态值,请使用触发器。 See http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html and in particular, triggers on insert and update. 请参阅http://dev.mysql.com/doc/refman/5.0/en/create-trigger.html ,特别是插入和更新时的触发器。

-- You've clarified your question! - 你澄清了你的问题! I think stored procedures are more what you are looking for now! 我认为存储过程更像是你现在正在寻找的东西!

http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html

This lets you create a function inside MySQL called numFruit which returns the sum of the other two columns. 这允许您在MySQL内部创建一个名为numFruit的函数,该函数返回其他两列的总和。

SELECT (numPears + numApples) AS numFruit FROM strange_table WHERE fruitID = 1;

If you are using PHP 如果您使用的是PHP

$pears = 5;
$apples= 1;

$query = "INSERT INTO strange_table (fruitID, numPears, numApples, numFruit) VALUES (1, $pears, $apples, " . ($pears + $apples) . ")";

你所谈论的是一个“计算列”它看起来不像MySql目前支持那些。

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

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