조인(Joins)
두 테이블의 컬럼을 모두 선택하지 않거나 두 테이블 간에 정의된 관계가 없어도, 테이블의 .join() 메서드를 사용해 다른 테이블과 조인하여 쿼리와 관련된 추가 데이터를 가져올 수 있습니다. join()은 첫 번째 인수로 조인할 테이블 객체를, 두 번째 인수로 테이블 간의 관련성을 나타내는 조건을 받습니다. 마지막으로, 선택문에 .select_from() 메서드를 사용해 조인 절을 감쌉니다. 예를 들어, 영상에서 Jason은 census 테이블의 state 컬럼이 state_fact 테이블의 name 컬럼과 대응되도록 census 테이블을 state_fact 테이블과 조인하기 위해 다음 코드를 실행했습니다.
stmt = stmt.select_from(
census.join(
state_fact, census.columns.state ==
state_fact.columns.name)
이 연습은 강의의 일부입니다
Python으로 배우는 데이터베이스 입문
연습 안내
census와state_fact테이블에서 모든 컬럼을 선택하는 구문을 작성하세요. 예를 들어 두 테이블employees와sales에서 모든 컬럼을 선택하려면stmt = select([employees, sales])를 사용합니다.stmt에select_from을 추가하여,census의state컬럼과state_fact의name컬럼을 기준으로census테이블을state_fact테이블과 조인하세요.- 구문을 실행해 첫 번째 결과를 가져와
result로 저장하세요. 이 코드는 이미 작성되어 있습니다. - 결과 객체의 키를 순회하며 각 키와 값을 출력하도록 답안을 Submit Answer 하세요!
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Build a statement to select the census and state_fact tables: stmt
stmt = select([____, ____])
# Add a select_from clause that wraps a join for the census and state_fact
# tables where the census state column and state_fact name column match
stmt_join = stmt.select_from(
____(____, census.columns.____ == state_fact.columns.____))
# Execute the statement and get the first result: result
result = connection.execute(stmt_join).first()
# Loop over the keys in the result object and print the key and value
for key in result.keys():
print(key, getattr(result, key))