在MySQL中删除第n行?
要在MySQL中删除第n行,请使用DELETE语句并使用子查询。让我们首先创建一个表:
mysql> create table DemoTable1 -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar(100) -> );
以下是使用insert命令在表中插入一些记录的查询:
mysql> insert into DemoTable1(StudentName) values('Larry'); mysql> insert into DemoTable1(StudentName) values('Sam'); mysql> insert into DemoTable1(StudentName) values('Mike'); mysql> insert into DemoTable1(StudentName) values('Carol'); mysql> insert into DemoTable1(StudentName) values('David'); mysql> insert into DemoTable1(StudentName) values('Bob');
以下是使用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);
显示表中的所有记录以检查记录是否已删除:
mysql> select * from DemoTable1;
这将产生以下输出。记录2nd现在被删除:
+-----------+-------------+ | StudentId | StudentName | +-----------+-------------+ | 1 | Larry | | 3 | Mike | | 4 | Carol | | 5 | David | | 6 | Bob | +-----------+-------------+ 5 rows in set (0.00 sec)