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

การลบระเบียนที่ระบุ

การใช้ where() clause ช่วยให้กำหนดเป้าหมายของ delete statement ได้อย่างแม่นยำ เพื่อลบเฉพาะระเบียนที่ต้องการ ตัวอย่างเช่น Jason ลบแถวทั้งหมดในตาราง employees ที่มี id เป็น 3 ด้วย delete statement ต่อไปนี้:

delete(employees).where(employees.columns.id == 3) 

ในแบบฝึกหัดนี้ จะลบแถว ทั้งหมด ที่มีค่า 'M' ในคอลัมน์ sex และค่า 36 ในคอลัมน์ age โดยโค้ดที่เตรียมไว้ให้ตอนต้นจะคำนวณจำนวนแถวทั้งหมดเหล่านี้ ซึ่งสำคัญมากที่ต้องตรวจสอบให้แน่ใจว่าจำนวนแถวที่ลบออกไปตรงกับค่าดังกล่าว

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

Python เบื้องต้นสำหรับฐานข้อมูล

ดูคอร์ส

คำแนะนำการฝึกหัด

  • สร้าง delete statement เพื่อลบข้อมูลออกจากตาราง census แล้วบันทึกไว้ในตัวแปร delete_stmt
  • ต่อ where clause เข้ากับ delete_stmt โดยใช้ and_ เพื่อกรองแถวที่มีค่า 'M' ในคอลัมน์ sex และ ค่า 36 ในคอลัมน์ age
  • รัน delete statement
  • ส่งคำตอบเพื่อพิมพ์ค่า rowcount ของ results พร้อมกับ to_delete ซึ่งแสดงจำนวนแถวที่ควรถูกลบ ค่าทั้งสองควรตรงกัน ซึ่งเป็นการตรวจสอบความถูกต้องที่สำคัญ!

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

# Build a statement to count records using the sex column for Men ('M') age 36: count_stmt
count_stmt = select([func.count(census.columns.sex)]).where(
    and_(census.columns.sex == 'M',
         census.columns.age == 36)
)

# Execute the select statement and use the scalar() fetch method to save the record count
to_delete = connection.execute(count_stmt).scalar()

# Build a statement to delete records from the census table: delete_stmt
delete_stmt = ____

# Append a where clause to target Men ('M') age 36: delete_stmt
delete_stmt = delete_stmt.____(
    ____(census.columns.sex == ____,
         ____ == ____)
)

# Execute the statement: results
results = connection.execute(____)

# Print affected rowcount and to_delete record count, make sure they match
print(results.rowcount, to_delete)
แก้ไขและรันโค้ด