Correlated updates
You can also update records with data from a select statement. This is called a
correlated update. It works by defining a select statement that returns the
value you want to update the record with and assigning that select statement as the value in
update.
You'll be using a flat_census in this exercise as the target of your correlated update. The flat_census table is a summarized copy of your census table, and contains, in particular, the fips_state columns.
Cet exercice fait partie du cours
Introduction to Databases in Python
Instructions
- Build a statement to select the
namecolumn fromstate_fact. Save the statement asfips_stmt. - Append a where clause to
fips_stmtthat matchesfips_statefrom thestate_facttable withfips_codein theflat_censustable. - Build an update statement to set the
state_nameinflat_censustofips_stmt. Save the statement asupdate_stmt. - Submit the answer to execute
update_stmt, store theresultsand print therowcountofresults.
Exercice interactif pratique
Essayez cet exercice en complétant cet exemple de code.
# 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)