开始使用免费开始使用

从表中筛选数据 - 进阶

您做得很熟练了!SQLAlchemy 还允许使用 and_()or_()not_() 等连接词来构建更复杂的筛选。例如,我们可以用下面的代码获取纽约州中年龄为 21 或 37 岁的人员记录集:

select([census]).where(
  and_(census.columns.state == 'New York',
       or_(census.columns.age == 21,
          census.columns.age == 37
         )
      )
  )

等价的 SQL 语句例如:

SELECT * FROM census WHERE state = 'New York' AND (age = 21 OR age = 37)

本练习是课程的一部分

Python 中的数据库入门

查看课程

练习说明

  • sqlalchemy 模块导入 and_
  • census 表选择所有记录。
  • 追加一个 where 子句,筛选 state'California'sex 不为 'M' 的所有记录。
  • 在连接中执行 stmt,并遍历 ResultProxy,打印每条记录中的 agesex 列。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# Import and_
from ____ import ____

# Build a query for the census table: stmt
stmt = select(____)

# Append a where clause to select only non-male records from California using and_
stmt = stmt.where(
    # The state of California with a non-male sex
    ____(census.columns.state == ____,
         census.columns.sex != ____
         )
)

# Loop over the ResultProxy printing the age and sex
for result in ____:
    print(____, ____)
编辑并运行代码