要只删除特定的行,请使用MySQL NOT IN()
。让我们首先创建一个表-
mysql> create table DemoTable1830 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(20) )AUTO_INCREMENT=101;
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1830(StudentName) values('Chris'); mysql> insert into DemoTable1830(StudentName) values('David'); mysql> insert into DemoTable1830(StudentName) values('Mike'); mysql> insert into DemoTable1830(StudentName) values('Sam'); mysql> insert into DemoTable1830(StudentName) values('Bob');
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1830;
这将产生以下输出-
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 101 | Chris | | 102 | David | | 103 | Mike | | 104 | Sam | | 105 | Bob | +-----------+-------------+ 5 rows in set (0.00 sec)
这是仅删除特定行的查询-
mysql> delete from DemoTable1830 where StudentId NOT IN('101','103','105');
让我们再次检查表记录:
mysql> select * from DemoTable1830;
这将产生以下输出-
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 101 | Chris | | 103 | Mike | | 105 | Bob | +-----------+-------------+ 3 rows in set (0.00 sec)