简体   繁体   English

使用子查询更新总计列

[英]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. 基本上,我有两个表: student_testsstudent_answers ,测试ID映射到了student_answers表。 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. 我想要一个子查询,在这里我可以求和特定测试ID的所有学生答案的总和,然后更新测试表中student_tests表中的分数列。

Am i doing something wrong with the where clause here? 我在这里的where子句上做错什么了吗? or is it something else? 或者是别的什么?

You should phrase this as an update / join explicitly, rather than having the join condition in the where clause. 您应该将此明确地表述为update / join ,而不是在where子句中具有join条件。

Your problem is that you have no group by in the subquery. 您的问题是您在子查询中没有group by The extra join to student_tests seems unnecessary, so try this: 似乎不需要额外加入student_tests ,因此请尝试以下操作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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