Correlated updates
นอกจากนี้ยังสามารถอัปเดตระเบียนด้วยข้อมูลจากคำสั่ง select ได้ วิธีนี้เรียกว่า
correlated update โดยทำงานด้วยการกำหนดคำสั่ง select ที่คืนค่าที่ต้องการอัปเดต แล้วกำหนดคำสั่ง select นั้นเป็นค่าใน
update
ในแบบฝึกหัดนี้จะใช้ตาราง flat_census เป็นเป้าหมายของ correlated update ตาราง flat_census คือสำเนาแบบสรุปของตาราง census และมีคอลัมน์ fips_state อยู่ด้วย
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
Python เบื้องต้นสำหรับฐานข้อมูล
คำแนะนำการฝึกหัด
- สร้างคำสั่งเพื่อเลือกคอลัมน์
nameจากตารางstate_factแล้วบันทึกคำสั่งนั้นเป็นfips_stmt - ต่อ where clause เข้ากับ
fips_stmtเพื่อจับคู่fips_stateจากตารางstate_factกับfips_codeในตารางflat_census - สร้างคำสั่ง update เพื่อกำหนดค่า
state_nameในตารางflat_censusให้เป็นfips_stmtแล้วบันทึกคำสั่งนั้นเป็นupdate_stmt - กด ส่งคำตอบ เพื่อรัน
update_stmtจากนั้นเก็บผลลัพธ์ไว้ในตัวแปรresultsและแสดงrowcountของresults
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# 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)