删除 MySQL 中的第 n 行?\

mysqlmysqli database

要删除 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)

相关文章