简体   繁体   中英

Add a new column with aggregate query into an existing table in mysql

The two tables are:

  1. student (student_id, student_name);

  2. score (student_id, subject, score1, score2).

and I want to add a new column to student table to find the average score of all subjects for each student. How can I do that?

Add your score column in students table and then you can update students table with average score like

UPDATE 
  student s 
  JOIN 
    (SELECT 
      student_id,
      AVG(score1 + score2) score 
    FROM
      score 
    GROUP BY student_id) sc 
  ON s.`student_id` = sc.student_id 
SET s.`score` = sc.score 

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