2011-10-20 3 views
0

J'ai une table comme celui-ciComment écrire ce genre de requête dans mysql?

 

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



Ceci est ma table, je dois mettre à jour champ de comptage total à l'aide d'une seule requête. Comment puis-je écrire ce genre de requête? je besoin d'une sortie comme ceci

 

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

+1

Ceci est une requête de mise à jour très trivial. Qu'avez-vous essayé jusqu'à présent? :) –

+0

J'ai besoin d'une requête comme celle-ci – learner

Répondre

5

Pour mettre à jour les valeurs de ces champs de la table:

UPDATE mytable SET total_count = a_count + b_count 

Pour obtenir les champs de la table:

SELECT a_count, b_count, total_count FROM mytable 

Pour obtenir les champs sans cette colonne total_count:

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

Vous pouvez également écrire un déclencheur pour que

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