按单列排序
若要按某个字段对查询结果排序,请使用 .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])