SQL基礎語法—delete語句


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關鍵詞表示刪除語句需要等待其他鏈接的讀此表操作結束后再執行,只作用在MylSAMMEMORYMERGE存儲引擎

  • 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';


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM