在 MySQL 中使用 ID 從表中刪除多行資料?


你可以使用 IN 語句來使用 MySQL 中的 ID 從表中刪除多行資料。語法如下:-

delete from yourTableName where yourColumnName in(value1,value2,.....valueN);

為了理解以上語法,讓我們建立一個表。以下是建立表的查詢。

mysql> create table DeleteManyRows
   −> (
   −> Id int,
   −> Name varchar(200),
   −> Age int
   −> );
Query OK, 0 rows affected (3.35 sec)

使用 insert 命令在表中插入一些記錄。查詢如下:-

mysql> insert into DeleteManyRows values(1,'John',23);
Query OK, 1 row affected (0.66 sec)

mysql> insert into DeleteManyRows values(2,'Johnson',22);
Query OK, 1 row affected (0.48 sec)

mysql> insert into DeleteManyRows values(3,'Sam',20);
Query OK, 1 row affected (0.39 sec)

mysql> insert into DeleteManyRows values(4,'David',26);
Query OK, 1 row affected (0.35 sec)

mysql> insert into DeleteManyRows values(5,'Carol',21);
Query OK, 1 row affected (0.10 sec)

mysql> insert into DeleteManyRows values(6,'Smith',29);
Query OK, 1 row affected (0.14 sec)

使用 select 語句從表中顯示所有記錄。查詢如下:-

mysql> select *from DeleteManyRows;

以下為輸出:-

+------+---------+------+
| Id   | Name    | Age |
+------+---------+------+
| 1    | John    | 23   |
| 2    | Johnson | 22   |
| 3    | Sam     | 20   |
| 4    | David   | 26   |
| 5    | Carol   | 21   |
| 6    | Smith   | 29   |
+------+---------+------+
6 rows in set (0.00 sec)

以下是使用 IN 語句從表中刪除行的查詢。查詢如下:-

mysql> delete from DeleteManyRows where Id in(1,2,3,4);
Query OK, 4 rows affected (0.25 sec)

讓我們在刪除多行(如 1,2,3,4)之後檢視有多少行。查詢如下:-

mysql> select *from DeleteManyRows;

以下為輸出:-

+------+-------+------+
| Id   | Name  | Age  |
+------+-------+------+
|    5 | Carol | 21   |
|    6 | Smith | 29   |
+------+-------+------+
2 rows in set (0.00 sec)

更新於: 30-Jul-2019

996 瀏覽量

開啟你的 職業生涯

完成該課程以獲得認證

開始
廣告