在 MySQL 中使用 id 从表中删除多行?

mysqlmysqli database

您可以使用 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)

相关文章