以單一欄位排序
若要依某個欄位排序查詢結果,使用 .order_by() 方法。預設情況下,.order_by() 會依提供的欄位由小到大排序。你只需要把想排序的欄位名稱傳給 .order_by() 即可。
例如在影片中,Jason 使用 stmt.order_by(census.columns.state),讓結果依 state 欄位排序。
本練習屬於課程
Python 資料庫入門
練習說明
- 從
census資料表選取state欄位的所有紀錄。為此,將census.columns.state以清單形式傳給select()。 - 串接
.order_by(),讓結果依state欄位排序。 - 在
connection上使用.execute()來執行stmt,並用.fetchall()取回所有結果。 - 列印
results的前 10 列。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Build a query to select the state column: stmt
stmt = ____
# Order stmt by the state column
stmt = ____
# Execute the query and store the results: results
results = ____
# Print the first 10 results
print(____[:10])