Question stem:
Write an UPDATE statement to calculate the average score of each student and fill it in the avg_grade field in the student table.
Table Structure:
The SQL statement defining the table structure is as follows:
CREATE TABLE student (
sno varchar(6) NOT NULL ,
sname varchar(10) ,
sex char(2) ,
nation char(2) ,
pnum char(18) ,
birth date ,
phone char( 11) ,
dept varchar(20) ,
avg_grade float(4,2),
PRIMARY KEY (sno)
) ;
CREATE TABLE score (
sno varchar(6) NOT NULL,
cno varchar(6) NOT NULL,
term varchar(15),
grade int(11),
PRIMARY KEY (sno,cno)
) ;
table sample
The table sample corresponding to the above table structure, some data are as follows:
student
surface:
score
surface:
Sample output:
Sample output, part of the data is as follows:
When writing this question, there was an error that I have never encountered before:
mysql报错:1093 - You can't specify target table 'student' for update in FROM clause
It means: In a SQL statement, you cannot first query a certain value in a table and then change the table
It is not possible to query and modify in the same table at the same time
My code: directly modify the average value obtained from the query as the modified content
Solution: Use the found information as a new virtual table, perform query work in the virtual table and then modify the student table
ac source code:
update student
set avg_grade=(
select s.avg_grade from(
select student.sno,round(avg(grade),2) as avg_grade
from score,student
where score.sno = student.sno
group by student.sno
)s
where student.sno = s.sno)