從資料表篩選資料 - 運算式
除了標準的 Python 比較運算子之外,你也可以使用像是
in_() 這類方法,來建立更強大的 where() 子句。完整的運算式清單請見 SQLAlchemy Documentation。
當 in_() 用在欄位上時,可以包含欄位值位於一組可能值清單中的紀錄。例如,where(census.columns.age.in_([20, 30, 40])) 只會回傳年齡正好為 20、30 或 40 歲的人的紀錄。
在這個練習中,你會繼續使用 census 資料表,並選出來自人口密度最高的 3 個州的人員紀錄。這些州名的清單已經替你建立好了。
本練習屬於課程
Python 資料庫入門
練習說明
- 從
census資料表選取所有紀錄。 - 修改
where子句的引數,使用in_(),回傳所有census.columns.state欄位的值存在於states清單中的紀錄。 - 對 ResultProxy
connection.execute(stmt)進行迴圈,並列印每筆紀錄的state與pop2000欄位。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# 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(____, ____)