相关更新
您也可以使用来自 select 语句的数据来更新记录,这称为相关更新(correlated update)。其做法是先定义一个 select 语句,使其返回用于更新记录的值,然后把该 select 语句作为值传入 update。
在本练习中,您将以 flat_census 作为相关更新的目标表。flat_census 是 census 表的汇总副本,尤其包含 fips_state 列。
本练习是课程的一部分
Python 中的数据库入门
练习说明
- 构建一个从
state_fact选择name列的语句,并将其保存为fips_stmt。 - 为
fips_stmt追加一个 where 子句,使state_fact表中的fips_state与flat_census表中的fips_code相匹配。 - 构建一个更新语句,将
flat_census中的state_name设为fips_stmt,并将该语句保存为update_stmt。 - 提交答案以执行
update_stmt,将结果存为results,并打印results的rowcount。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# 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)