상관 업데이트
select 구문의 결과를 사용해 레코드를 업데이트할 수도 있습니다. 이를 상관 업데이트(correlated update)라고 합니다. 업데이트하려는 값을 반환하는 select 구문을 정의하고, 그 select 구문을 update에서 값으로 지정하는 방식으로 동작합니다.
이번 연습에서는 상관 업데이트의 대상 테이블로 flat_census를 사용합니다. flat_census 테이블은 census 테이블을 요약한 사본으로, 특히 fips_state 열을 포함하고 있습니다.
이 연습은 강의의 일부입니다
Python으로 배우는 데이터베이스 입문
연습 안내
state_fact에서name열을 선택하는 구문을 작성하고fips_stmt로 저장하세요.fips_stmt에 where 절을 추가하여state_fact의fips_state와flat_census의fips_code가 일치하도록 하세요.flat_census의state_name을fips_stmt로 설정하는 업데이트 구문을 작성하고, 이를update_stmt로 저장하세요.- 답변 제출하여
update_stmt를 실행하고,results를 저장한 뒤results의rowcount를 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Build a statement to select name from state_fact: fips_stmt
fips_stmt = select([____])
# Append a where clause to match the fips_state to flat_census fips_code: fips_stmt
fips_stmt = fips_stmt.____(
____ == ____)
# Build an update statement to set the name to fips_stmt_where: update_stmt
update_stmt = update(____).values(____=____)
# Execute update_stmt: results
results = connection.execute(update_stmt)
# Print rowcount
print(results.rowcount)