在 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)
广告