데이터베이스설계

[데이터베이스설계] 3-16 updates with Scalar 서브쿼리

젼젼39 2025. 2. 15. 22:58
updates
with
Scalar
서브쿼리
Q) recompute and update tot_creds value for all students
=> update student S
    set tot_cred = ( select sum(credits)          //scalar 서브쿼리가 산출하는 값을 여기 할당
.                             from takes, course
.                             where takes.course_id = course.course_id and  //학점을 얻기위해 정보대조
                                          S.ID = takes.ID and                // 이 학생이 수강한것들만
                                          takes.grade <> ‘F’ and             // F가 아니어야 함
                                          takes.grade is not null );            //null을 세지 않게.
 
//레코드가 1도 없어서 where절을 충족하는 투플이 1개도 없게되면 sum 0이 아니고 null리턴
    -> select sum(credits) 자리에, select (case ~~) 넣기
=> update student S
     set tot_cred = ( select ( case
                                               when sum(credits) is not null then sum(credits)
                                               else 0                            //null이 아니라 0을 넣게된다
                                           end )
                    .         from takes, course
                    .         where takes.course_id = course.course_id and
                                         S.ID = takes.ID and
                                         takes.grade <> ‘F’ and
                                         takes.grade is not null );