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. 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
.
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.
-- 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
This lets you create a function inside MySQL called numFruit which returns the sum of the other two columns.
SELECT (numPears + numApples) AS numFruit FROM strange_table WHERE fruitID = 1;
If you are using PHP
$pears = 5;
$apples= 1;
$query = "INSERT INTO strange_table (fruitID, numPears, numApples, numFruit) VALUES (1, $pears, $apples, " . ($pears + $apples) . ")";
What you are talking about is called a "computed column" It doesn't look like MySql currently supports those.