开始使用免费开始使用

相关更新

您也可以使用来自 select 语句的数据来更新记录,这称为相关更新(correlated update)。其做法是先定义一个 select 语句,使其返回用于更新记录的值,然后把该 select 语句作为值传入 update

在本练习中,您将以 flat_census 作为相关更新的目标表。flat_censuscensus 表的汇总副本,尤其包含 fips_state 列。

本练习是课程的一部分

Python 中的数据库入门

查看课程

练习说明

  • 构建一个从 state_fact 选择 name 列的语句,并将其保存为 fips_stmt
  • fips_stmt 追加一个 where 子句,使 state_fact 表中的 fips_stateflat_census 表中的 fips_code 相匹配。
  • 构建一个更新语句,将 flat_census 中的 state_name 设为 fips_stmt,并将该语句保存为 update_stmt
  • 提交答案以执行 update_stmt,将结果存为 results,并打印 resultsrowcount

交互式实操练习

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

# Build a statement to select name from state_fact: fips_stmt
fips_stmt = select([____])

# Append a where clause to match the fips_state to flat_census fips_code: fips_stmt
fips_stmt = fips_stmt.____(
    ____ == ____)

# Build an update statement to set the name to fips_stmt_where: update_stmt
update_stmt = update(____).values(____=____)

# Execute update_stmt: results
results = connection.execute(update_stmt)

# Print rowcount
print(results.rowcount)
编辑并运行代码