开始使用免费开始使用

按单列排序

若要按某个字段对查询结果排序,请使用 .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])
编辑并运行代码