開始使用免費開始

從資料表篩選資料 - 基礎

已經連線到資料庫,現在來練習如何在查詢中做篩選!

影片中提到,where() 子句可用來篩選陳述式所回傳的資料。例如,若要從 census 資料表選取性別為女性(或 'F')的所有紀錄,可以這麼做:

select([census]).where(census.columns.sex == 'F')

除了 ==,你也可以在 where() 子句中使用幾乎所有 Python 比較運算子(例如 <=!= 等)。

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • census 以清單形式傳給 select(),以選取 census 資料表中的所有紀錄。
  • stmt 後加入 where 子句,只回傳 state'New York' 的紀錄。
  • connection.execute() 執行陳述式 stmt,並用 .fetchall() 取回結果。
  • 走訪 results,對每筆紀錄印出 agesexpop2000 欄位。例如,可以用 result.age 印出 resultage

動手互動練習

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

# Create a select query: stmt
stmt = ____

# Add a where clause to filter the results to only those for New York : stmt_filtered
stmt = stmt.____

# Execute the query to retrieve all the data returned: results
results = ____

# Loop over the results and print the age, sex, and pop2000
for ___ in ____:
    print(result.age, ____, ____)
編輯並執行程式碼