使用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)
阅读更多:MySQL 教程