시작하기무료로 시작하기

테이블에서 선택한 데이터 필터링 - Expressions

표준 Python 비교 연산자 외에도 in_() 같은 메서드를 사용해 더 강력한 where() 절을 만들 수 있어요. 전체 표현식 목록은 SQLAlchemy Documentation에서 확인하실 수 있어요.

열에 대해 in_() 메서드를 사용하면, 해당 열의 값이 가능한 값 목록에 포함되는 레코드만 포함할 수 있어요. 예를 들어 where(census.columns.age.in_([20, 30, 40]))는 정확히 20, 30, 40세인 사람들의 레코드만 반환해요.

이번 연습에서는 census 테이블을 계속 사용해, 인구 밀도가 가장 높은 세 개 주의 사람들에 대한 레코드를 선택할 거예요. 그 주들의 목록은 이미 states로 준비되어 있어요.

이 연습은 강의의 일부입니다

Python으로 배우는 데이터베이스 입문

강의 보기

연습 안내

  • census 테이블에서 모든 레코드를 선택하세요.
  • where 절의 인수를 수정해 in_()을 사용하고, census.columns.state 열의 값이 states 리스트에 포함된 모든 레코드를 반환하세요.
  • ResultProxy connection.execute(stmt)를 순회하면서 각 레코드의 statepop2000 열을 출력하세요.

실습형 인터랙티브 연습

이 예제를 이 샘플 코드를 완성하여 풀어보세요.

# Define a list of states for which we want results
states = ['New York', 'California', 'Texas']

# Create a query for the census table: stmt
stmt = select(____)

# Append a where clause to match all the states in_ the list states
stmt = stmt.where(____)

# Loop over the ResultProxy and print the state and its population in 2000
for ____ in connection.execute(____):
    print(____, ____)
코드 편집 및 실행