始める無料で始める

相関更新(Correlated updates)

select ステートメントの結果を使ってレコードを更新することもできます。これは相関更新(correlated update)と呼ばれます。更新したい値を返す 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_censusstate_namefips_stmt に設定する更新ステートメントを作成し、update_stmt として保存します。
  • Submit Answer して 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)
コードを編集して実行