【问题标题】:mysql update table column from a select statement with countmysql从带有计数的select语句更新表列
【发布时间】:2015-01-13 03:56:48
【问题描述】:

我正在研究一些 MySQL,但遇到了一些问题。

我正在尝试使用学生所学学分的正确数量来更新列,但目前当我计算所学学分时,我会得到所有学生所学学分的总数。我

学生桌

ID  varchar(5)  
name    varchar(20) 
dept_name   varchar(20) 
tot_cred    decimal(3,0)

上桌

ID  varchar(5)  
course_id   varchar(8)  
sec_id  varchar(8)  
semester    varchar(6)  
year    decimal(4,0)    
grade   varchar(2)  

课程表

course_id   varchar(8)  
title   varchar(50) 
dept_name   varchar(20) 
credits decimal(2,0)    

这是我目前正在使用的声明。我还要加if they have an f then they don't get credit for the class that they took

update studentCopy set tot_cred = (
select sum(course.credits)
from student
left join takes on student.ID = takes.ID
left join course on takes.course_id = course.course_id
where student.ID = student.ID
group by studentCopy.ID);

任何帮助将不胜感激。提前致谢!

【问题讨论】:

    标签: mysql select join sql-update


    【解决方案1】:

    以下是对您的查询的一些简化:

    • left joins 是不必要的。你可以使用join
    • group by 是不必要的。事实上,它具有误导性,因为它暗示子查询可能返回多行(这会产生错误)。
    • Student 表是不必要的;您可以将关联子句目录写入takes
    • 表别名使查询更易于编写和阅读。

    所以,我会把你的查询写成:

    update studentCopy sc
        set tot_cred = (select sum(c.credits)
                        from takes t join
                             course c
                             on t.course_id = c.course_id
                        where sc.ID = t.ID
                       );
    

    您可以在where 子句中添加成绩条件:

    update studentCopy sc
        set tot_cred = (select sum(c.credits)
                        from takes t join
                             course c
                             on t.course_id = c.course_id
                        where sc.ID = t.ID and grade <> 'f'
                       );
    

    【讨论】:

      【解决方案2】:

      我刚才确实得到了部分答案。我变了

      where student.ID = student.ID
      

      where studentCopy.ID = student.ID
      

      给我自己学分的结果。只是努力获得 if Grade = 'F' 然后不要计算成绩。

      【讨论】:

        猜你喜欢
        • 2018-07-29
        • 2017-01-15
        • 1970-01-01
        • 2022-11-20
        • 1970-01-01
        • 2010-11-06
        • 1970-01-01
        • 2014-05-15
        • 2019-03-17
        相关资源
        最近更新 更多