開始使用免費開始

刪除特定記錄

使用 where() 子句,你可以讓 delete 敘述只移除特定記錄。舉例來說,Jason 以以下刪除敘述刪除了 employees 資料表中 id 為 3 的所有列:

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

在這裡,你將刪除所有在 sex 欄位為 'M',且在 age 欄位為 36 的列。我們在開頭已提供用來計算這些列總數的程式碼。請務必確認你實際刪除的列數與此數字相同。

本練習屬於課程

Python 資料庫入門

檢視課程

練習說明

  • 建立一個 delete 敘述,從 census 資料表移除資料。將其儲存為 delete_stmt
  • delete_stmt 後串接一個 where 子句,內含 and_,用來篩選 sex 欄位為 'M'age 欄位為 36 的列(兩個條件必須同時成立)。
  • 執行這個刪除敘述。
  • 送出答案以列印 resultsrowcount,以及 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)
編輯並執行程式碼