2011-01-31 153 views
1

我有2場一個MySQL表:numPears(int)和numApples(INT),我想有一個numFruit(INT),可自動獲得這2個值,總結他們。那可能嗎?總和兩個領域

因此,如果查詢

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

,然後查詢

SELECT numFruit FROM strange_table WHERE fruitID = 1; 

它返回我6

回答

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

我可以在sql語句中選擇其他的東西嗎? – Shoe 2011-01-31 17:11:20

+0

是的,只需在'numFruit'後面添加一個逗號並添加您想要檢索的其他列: - SELECT(numPears + numApples)AS numFruit,numPears,numApples FROM strange_table WHERE fruitID = 1; – Purpletoucan 2011-01-31 17:14:22

0

如果您使用的是PHP

$pears = 5; 
$apples= 1; 

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

你所講的被稱爲「計算列」它看起來並不像MySQL目前支持的。