關聯式更新(Correlated updates)
你也可以用 select 陳述式回傳的資料來更新記錄。這稱為關聯式更新。作法是先定義一個會回傳你要用來更新記錄之值的 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)