mysql - 使用子查询更新总计列

标签 mysql sql

这是我的查询:

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 

没有错误,但它说零行受到影响。

基本上,我有两个表:student_testsstudent_answers,测试 ID 映射到 student_answers 表。我想要一个子查询,可以在其中对特定测试 ID 的所有学生答案求和,然后更新测试表中的 student_tests 表中的分数列。

我在这里的 where 子句做错了什么吗?还是别的什么?

最佳答案

您应该明确地将其表述为 update/join,而不是在 where 中使用 join 条件> 条款。

您的问题是子查询中没有group by。额外加入 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

关于mysql - 使用子查询更新总计列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27239359/

相关文章:

c# - ASP.NET 上的数据库驱动的依赖动态 DropDownList

PHP - 搜索结果不分页

mysql - Laravel 6.0 迁移 - SQLSTATE[HY000] [2002] 没有这样的文件或目录

sql - redshift select distinct 返回重复值

sql - 联合 SQL Server 表中的所有几何图形,如 Postgres 中的 GeomUnion

php - preg_replace php中特定的sql列

php - 在 php 中的 if 语句中分配给 var

c# - 检查 NULL 重复项的 SQL 不返回

MySQL - 从所有表中选择列

sql - SELECT DISTINCT 值并 INSERT INTO 表