相関更新(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_censusのstate_nameをfips_stmtに設定する更新ステートメントを作成し、update_stmtとして保存します。- Submit Answer して
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)