开始使用免费开始使用

删除特定记录

通过使用 where() 子句,您可以让 delete 语句只删除特定记录。例如,Jason 使用如下删除语句删除了 employees 表中所有 id 为 3 的行:

delete(employees).where(employees.columns.id == 3) 

在本题中,您将删除 sex 列为 'M'age 列为 36 的所有行。我们在开头提供了用于计算这类行总数的代码。请务必确保该数值与您实际删除的行数一致。

本练习是课程的一部分

Python 中的数据库入门

查看课程

练习说明

  • 构建一个 delete 语句,从 census 表中删除数据。将其保存为 delete_stmt
  • delete_stmt 上追加一个 where 子句,其中包含 and_,用于筛选 sex 列为 'M'age 列为 36 的行(两者需同时满足)。
  • 执行该删除语句。
  • 提交答案以打印 resultsrowcount,以及 to_delete(表示应删除的行数)。两者应当相同,这是一个重要的一致性检查!

交互式实操练习

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

# Build a statement to count records using the sex column for Men ('M') age 36: count_stmt
count_stmt = select([func.count(census.columns.sex)]).where(
    and_(census.columns.sex == 'M',
         census.columns.age == 36)
)

# Execute the select statement and use the scalar() fetch method to save the record count
to_delete = connection.execute(count_stmt).scalar()

# Build a statement to delete records from the census table: delete_stmt
delete_stmt = ____

# Append a where clause to target Men ('M') age 36: delete_stmt
delete_stmt = delete_stmt.____(
    ____(census.columns.sex == ____,
         ____ == ____)
)

# Execute the statement: results
results = connection.execute(____)

# Print affected rowcount and to_delete record count, make sure they match
print(results.rowcount, to_delete)
编辑并运行代码