เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

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)
แก้ไขและรันโค้ด