在MySQL中获取除第一行和最后一行之外的所有行
要使所有行与第一行和最后一行分开,请与MIN()
和一起使用子查询MAX()
。让我们首先创建一个表-
mysql> create table DemoTable1917 ( StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, StudentCode int, StudentMarks int );
使用插入命令在表中插入一些记录-
mysql> insert into DemoTable1917(StudentCode,StudentMarks) values(78,95); mysql> insert into DemoTable1917(StudentCode,StudentMarks) values(78,96); mysql> insert into DemoTable1917(StudentCode,StudentMarks) values(78,97); mysql> insert into DemoTable1917(StudentCode,StudentMarks) values(78,98); mysql> insert into DemoTable1917(StudentCode,StudentMarks) values(78,99);
使用select语句显示表中的所有记录-
mysql> select * from DemoTable1917;
这将产生以下输出-
+-----------+-------------+--------------+ | StudentId | StudentCode | StudentMarks | +-----------+-------------+--------------+ | 1 | 78 | 95 | | 2 | 78 | 96 | | 3 | 78 | 97 | | 4 | 78 | 98 | | 5 | 78 | 99 | +-----------+-------------+--------------+ 5 rows in set (0.00 sec)
这是获取除第一行和最后一行之外的所有行的查询:
mysql> select * from DemoTable1917 where StudentId NOT IN ( ( select min(StudentId) from DemoTable1917 where StudentCode=78), (select max(StudentId) from DemoTable1917 where StudentCode=78) ) and StudentCode=78;
这将产生以下输出-
+-----------+-------------+--------------+ | StudentId | StudentCode | StudentMarks | +-----------+-------------+--------------+ | 2 | 78 | 96 | | 3 | 78 | 97 | | 4 | 78 | 98 | +-----------+-------------+--------------+ 3 rows in set (0.00 sec)