开始使用免费开始使用

从表中筛选数据 - 表达式

除了标准的 Python 比较符外,您还可以使用 in_() 等方法来构建更强大的 where() 子句。完整的表达式列表请参见 SQLAlchemy 文档

当在列上使用方法 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(____, ____)
编辑并运行代码