開始使用免費開始

關聯式更新(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_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)
編輯並執行程式碼