用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)
使用insert命令向表中插入一些记录 −
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)
阅读更多:MySQL 教程