简体   繁体   中英

Using Subquery to update total column

Here is my query:

UPDATE student_tests,
  (SELECT SUM(olc_sta_i_points_earned) AS total, olc_sta_i_stt_num FROM student_answers
     JOIN student_tests ON olc_sta_i_stt_num = olc_stt_i_num         
  ) AS a
SET student_tests.olc_stt_i_score = a.total
WHERE a.olc_sta_i_stt_num = student_tests.olc_stt_i_num 

There are no errors but it says zero rows are affected.

Basically I have two tables: student_tests and student_answers the test id is mapped to the student_answers tables. I want a subquery where I can sum all the student answers for the specific test id and then update the score column in the student_tests table in the tests table.

Am i doing something wrong with the where clause here? or is it something else?

You should phrase this as an update / join explicitly, rather than having the join condition in the where clause.

Your problem is that you have no group by in the subquery. The extra join to student_tests seems unnecessary, so try this:

UPDATE student_tests s JOIN
       (SELECT SUM(a.olc_sta_i_points_earned) AS total, a.olc_sta_i_stt_num
        FROM student_answers a     
        GROUP BY a.olc_sta_i_stt_num    
       ) AS a
       ON a.olc_sta_i_stt_num = t.olc_stt_i_num 
    SET s.olc_stt_i_score = a.total

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