删除 MySQL 中除特定行之外的所有行?

mysqlmysqli database

要删除除单个特定行之外的所有行,请尝试以下语法 −

delete from yourTableName where yourColumnName!=yourValue;

首先我们创建一个表 −

mysql> create table DemoTable
   (
   Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   Subject varchar(100)
   );
Query OK, 0 rows affected (0.65 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable(Subject) values('MySQL');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(Subject) values('MongoDB');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable(Subject) values('Java');
Query OK, 1 row affected (0.12 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable;

输出

+----+---------+
| Id | Subject |
+----+---------+
| 1  | MySQL   |
| 2  | MongoDB |
| 3  | Java    |
+----+---------+
3 rows in set (0.00 sec)

以下是删除除单个特定行 − 之外的所有行的查询

mysql> delete from DemoTable where Subject!='MongoDB';
Query OK, 2 rows affected (0.19 sec))

让我们再次检查表中的所有记录 −

mysql> select *from DemoTable;

输出

+----+---------+
| Id | Subject |
+----+---------+
| 2  | MongoDB |
+----+---------+
1 row in set (0.00 sec)

相关文章