简体   繁体   中英

How to write this kind of a query in mysql?

I have a table like this


    2                 3              
    5                 1
    4                 7
    5                 0

This is my table I need to update total count field using a single query. How can I write that kind of a query? I need output like this


    2                 3                   5
    5                 1                   6
    4                 7                   11
    5                 0                   5

To update the values of those fields in the table:

UPDATE mytable SET total_count = a_count + b_count

To get those fields from the table:

SELECT a_count, b_count, total_count FROM mytable

To get those fields without that total_count column:

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

You can also write a trigger for that

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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