開始使用免費開始

從資料表篩選資料 - 運算式

除了標準的 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) 進行迴圈,並列印每筆紀錄的 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(____, ____)
編輯並執行程式碼