Table에서 선택한 데이터 필터링 - 심화
이제 정말 익숙해지셨어요! SQLAlchemy에서는 and_(), or_(), not_() 같은 접속사를 사용해 더 복잡한 필터링을 만들 수도 있어요. 예를 들어, 다음 코드는 뉴욕에 살면서 나이가 21세 또는 37세인 사람들의 레코드를 가져옵니다:
select([census]).where(
and_(census.columns.state == 'New York',
or_(census.columns.age == 21,
census.columns.age == 37
)
)
)
이에 해당하는 SQL문은 예를 들어 다음과 같습니다.
SELECT * FROM census WHERE state = 'New York' AND (age = 21 OR age = 37)
이 연습은 강의의 일부입니다
Python으로 배우는 데이터베이스 입문
연습 안내
sqlalchemy모듈에서and_를 import 하세요.census테이블에서 모든 레코드를 선택하세요.state가'California'이고sex가'M'이 아닌 모든 레코드를 필터링하는 where 절을 추가하세요.- 연결에서
stmt를 실행하고 ResultProxy를 반복(iterate)하여 각 레코드의age와sex열을 출력하세요.
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Import and_
from ____ import ____
# Build a query for the census table: stmt
stmt = select(____)
# Append a where clause to select only non-male records from California using and_
stmt = stmt.where(
# The state of California with a non-male sex
____(census.columns.state == ____,
census.columns.sex != ____
)
)
# Loop over the ResultProxy printing the age and sex
for result in ____:
print(____, ____)