如何在 MySQL 中删除第 n 行?\n


要删除 MySQL 中的第 n 行,可以使用 DELETE 语句与子查询配合使用。让我们首先创建一个表

mysql> create table DemoTable1
   -> (
   -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentName varchar(100)
   -> );
Query OK, 0 rows affected (0.99 sec)

以下是使用 insert 命令在表中插入某些记录的查询

mysql> insert into DemoTable1(StudentName) values('Larry');
Query OK, 1 row affected (0.14 sec)

mysql> insert into DemoTable1(StudentName) values('Sam');
Query OK, 1 row affected (0.13 sec)

mysql> insert into DemoTable1(StudentName) values('Mike');
Query OK, 1 row affected (0.18 sec)

mysql> insert into DemoTable1(StudentName) values('Carol');
Query OK, 1 row affected (0.12 sec)

mysql> insert into DemoTable1(StudentName) values('David');
Query OK, 1 row affected (0.16 sec)

mysql> insert into DemoTable1(StudentName) values('Bob');
Query OK, 1 row affected (0.13 sec)

以下是使用 select 命令从表中显示记录的查询

mysql> select * from DemoTable1;

这将产生以下输出

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | Larry       |
| 2         | Sam         |
| 3         | Mike        |
| 4         | Carol       |
| 5         | David       |
| 6         | Bob         |
+-----------+-------------+
6 rows in set (0.00 sec)

以下是删除第 n 行的查询

mysql> delete from DemoTable1 where StudentId = (select StudentId from (select StudentId from DemoTable1 order by StudentId limit 1,1) as tbl);
Query OK, 1 row affected (0.19 sec)

从表中显示所有记录来检查记录是否已删除

mysql> select * from DemoTable1;

这将产生以下输出。现在的第 2nd 记录已删除

+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1         | Larry       |
| 3         | Mike        |
| 4         | Carol       |
| 5         | David       |
| 6         | Bob         |
+-----------+-------------+
5 rows in set (0.00 sec)

更新于: 30-7-2019

816 次浏览

开启您的 职业生涯

完成课程即可获得认证

开始使用
广告