2011-10-20 34 views
0

我有這樣如何在mysql中編寫這種查詢?

 

    a_count  b_count   total_count(a_count+b_count) 
    2     3    
    5     1 
    4     7 
    5     0 



這一個表是我的表,我需要使用單個查詢來更新總數領域。我該如何編寫這種查詢? 我需要這樣的

 

    a_count  b_count   total_count(a_count+b_count) 
    2     3     5 
    5     1     6 
    4     7     11 
    5     0     5 

+1

這是一個很平凡的UPDATE查詢。你試過什麼了? :) –

+0

我需要這樣的查詢 – learner

回答

5

輸出要更新表中的字段的值:

UPDATE mytable SET total_count = a_count + b_count 

若要從表中獲取這些字段:

SELECT a_count, b_count, total_count FROM mytable 

要獲得這些領域沒有total_count列:

SELECT a_count, b_count, (a_count+b_count) AS total_count FROM mytable 
2

你也可以寫一個觸發器爲

DELIMITER // 
CREATE TRIGGER `total_count` BEFORE INSERT OR UPDATE on `table` 
FOR EACH ROW BEGIN 
SET NEW.total = NEW.a+NEW.b; 
END; 
// 
DELIMITER ;