仅使用 MySQL 删除表中的特定行
要仅删除特定行,请使用 MySQL NOT IN()。我们首先创建一个表 -
mysql> create table DemoTable1830 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentName varchar(20) )AUTO_INCREMENT=101; Query OK, 0 rows affected (0.00 sec)
使用插入命令在表中插入一些记录 -
mysql> insert into DemoTable1830(StudentName) values('Chris'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1830(StudentName) values('David'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1830(StudentName) values('Mike'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1830(StudentName) values('Sam'); Query OK, 1 row affected (0.00 sec) mysql> insert into DemoTable1830(StudentName) values('Bob'); Query OK, 1 row affected (0.00 sec)
使用 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'); Query OK, 2 rows affected (0.00 sec)
让我们再次检查表记录
mysql> select * from DemoTable1830;
这将产生以下输出 -
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 101 | Chris | | 103 | Mike | | 105 | Bob | +-----------+-------------+ 3 rows in set (0.00 sec)
广告