如何在 MySQL 中刪除除部分行以外的所有行?


對於不想刪除的行,可以使用 NOT IN 運算子。以下是語法 −

delete from yourTableName where yourColumnName NOT
IN(‘yourValue1’,‘yourValue2’,‘yourValue3’,.........N);

讓我們首先建立一個表 −

mysql> create table deleteAllRowsWithCondition
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(20)
   -> );
Query OK, 0 rows affected (0.84 sec)

以下是使用 insert 命令向表中插入一些記錄的查詢 −

mysql> insert into deleteAllRowsWithCondition(Name) values('Larry');
Query OK, 1 row affected (0.14 sec)

mysql> insert into deleteAllRowsWithCondition(Name) values('John');
Query OK, 1 row affected (0.21 sec)

mysql> insert into deleteAllRowsWithCondition(Name) values('Sam');
Query OK, 1 row affected (0.12 sec)

mysql> insert into deleteAllRowsWithCondition(Name) values('Mike');
Query OK, 1 row affected (0.16 sec)

mysql> insert into deleteAllRowsWithCondition(Name) values('Carol');
Query OK, 1 row affected (0.14 sec)

mysql> insert into deleteAllRowsWithCondition(Name) values('Bob');
Query OK, 1 row affected (0.06 sec)

mysql> insert into deleteAllRowsWithCondition(Name) values('David');
Query OK, 1 row affected (0.14 sec)

以下是使用 select 語句顯示錶中所有記錄的查詢 −

mysql> select * from deleteAllRowsWithCondition;

這將產生以下輸出 −

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Larry |
| 2  | John  |
| 3  | Sam   |
| 4  | Mike  |
| 5  | Carol |
| 6  | Bob   |
| 7  | David |
+----+-------+
7 rows in set (0.00 sec)

以下是刪除具有某些條件的所有行的查詢。我們在這裡不刪除“John”、“Mike”和“Carol” −

mysql> delete from deleteAllRowsWithCondition where Name NOT IN('John','Mike','Carol');
Query OK, 4 rows affected (0.15 sec)

讓我們檢查一下是否已從表中刪除某些行。以下是查詢 −

mysql> select * from deleteAllRowsWithCondition;

這將產生以下輸出 −

+----+-------+
| Id | Name  |
+----+-------+
| 2  | John  |
| 4  | Mike  |
| 5  | Carol |
+----+-------+
3 rows in set (0.00 sec)

更新於: 2019 年 7 月 30 日

6K+ 次瀏覽

開啟你的 職業

透過完成課程獲得認證

開始
廣告