获取 MySQL 中除第一行和最后一行之外的所有行


要获取除第一行和最后一行之外的所有行,请使用子查询以及 MIN() 和 MAX()。我们首先创建一个表 -

mysql> create table DemoTable1917
   (
   StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   StudentCode int,
   StudentMarks int
   );
Query OK, 0 rows affected (0.00 sec)

使用 insert 命令在表中插入一些记录 -

mysql> insert into DemoTable1917(StudentCode,StudentMarks) values(78,95);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1917(StudentCode,StudentMarks) values(78,96);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1917(StudentCode,StudentMarks) values(78,97);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1917(StudentCode,StudentMarks) values(78,98);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1917(StudentCode,StudentMarks) values(78,99);
Query OK, 1 row affected (0.00 sec)

使用 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)

更新于: 30-Dec-2019

128 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始
广告