1 delete語句介紹
delete
語句用於刪除表中已經存在的整行數據。基本語法如下:
Single-Table Syntax
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
Multiple-Table Syntax
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
tbl_name[.*] [, tbl_name[.*]] ...
FROM table_references
[WHERE where_condition]
DELETE [LOW_PRIORITY] [QUICK] [IGNORE]
FROM tbl_name[.*] [, tbl_name[.*]] ...
USING table_references
[WHERE where_condition]
-
tbl_name
關鍵詞代表刪除數據的目標表 -
where
子句代表被刪除數據的滿足條件,如果沒有where
子句則代表所有表數據都刪除 -
order by
子句代表刪除數據的順序 -
limit
子句代表被刪除數據的行數限制 -
low_priority
關鍵詞表示刪除語句需要等待其他鏈接的讀此表操作結束后再執行,只作用在MylSAM
,MEMORY
,MERGE
存儲引擎 -
quick
關鍵詞是在使用myisam
存儲引擎時,刪除操作不會合並刪除表的索引葉節點,這樣會在一定程度上加快刪除的速度 -
ignore
關鍵詞代表會忽略刪除過程中的一些錯誤
2 delete語句使用示例
2.1 單表刪除
單表刪除的一些案例如下:
## 刪除students中的所有數據
mysql> delete from students;
## 使用order by配合limit子句刪除sid最大的兩條數據
mysql> delete from students order by sid desc limit 2;
2.2 多表刪除
多表刪除是指從一個或多個表中刪除滿足條件的數據,其中的table_reference
代表了多個表的join
操作。多表刪除示例如下:
## 刪除students2表和students3表中sid相同的行
mysql> delete students2,student3 from students2 inner join students3 where students2.sid=students3.sid;
## 使用關聯兩張表進行查詢,但在刪除時只刪除單表中的行
mysql> delete students2 from students2 inner join students3 where students2.sid=students3.sid;
## 表的別名,只能在table_references子句中使用,否則會報錯
mysql> delete a from students2 as a inner join students3 as b where a.sid=b.sid
3 使用delete語句注意事項
- 在使用
delete
語句之前先使用查詢語句驗證過濾條件是否正確 - 添加事務
set autocommit=off
,開啟手動回滾操作
4 練習
刪除所有學號大於200的學生信息
mysql> delete from students where sid>200;
刪除系名為accounting的所有老師信息
mysql> selete id from dept where dept_name='accounting';
mysql> delete from teacher where dept_id=4;
## 當條件中的值不止一個時,此時不能使用'=',應該使用'in'關鍵字
mysql> delete from teacher where dept_id in (selete id from dept where dept_name in ('accounting'));
## 使用多表刪除
mysql> delete teacher from teacher inner join dept where teacher.dept_id=dept.id and dept.dept_name='accounting';