開始使用免費開始

從資料表篩選資料 - 進階

你已經越來越上手了!SQLAlchemy 也允許使用者使用 and_()or_()not_() 等連接詞來建立更複雜的篩選。例如,以下程式碼可以取得在 New York、年齡為 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_
  • census 資料表選取所有紀錄。
  • 加上一個 where 子句,篩選出 state'California',且 sex 不是 'M' 的所有紀錄。
  • 在連線中執行 stmt,並迭代 ResultProxy,對每筆紀錄印出 agesex 欄位。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# 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(____, ____)
編輯並執行程式碼