简体   繁体   中英

How should I update a MySQL table column with the average of other two columns?

I have a table with the following columns: id (AI, PK), name, surname, group, grade1, grade2, average and I must insert from a PHP script the average value of 'grade1' and 'grade2' in the 'average' column.

I have used:

INSERT INTO `table_name`(`average`) SELECT AVG((`grade1` + `grade2`)/2.0) FROM table_name GROUP BY `id`

I have the grades inserted, but somehow when I run the SQL statement, it creates new rows only with the average values. I need to UPDATE the column 'average' in the existing rows, not create new ones.

Thank you in advance!

You seem to want update , not insert :

update table_name
    set average = (grade1 + grade2) / 2;

I should note that having such a calculated column is dangerous, because it can get out-of-synch. Much safer are generated columns, which you can express as:

alter table table_name add column average decimal(10, 2)
    generated always as ( (grade1 + grade2) / 2);

This is calculated when the value is queried so it is always up-to-date.

You should use UPDATE... WHERE... instead of INSERT INTO...

I would also consider to use a trigger instead of using PHP.

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