如何查找MySQL列中第n大的值?
要查找列中第n大的值,需要使用ORDER BY DESC和LIMIT子句。如果要查找列的第二大值,请使用以下语法
SELECT *FROM yourTableName ORDER BY DESC yourColumnName LIMIT 1,1;
如果要查找列的第四大值,请使用以下语法
SELECT *FROM yourTableName ORDER BY DESC yourColumnName LIMIT 3,1;
如果要查找列的第一个最大值,请使用以下语法
SELECT *FROM yourTableName ORDER BY DESC yourColumnName LIMIT 1;
如上语法所述,只需要更改LIMIT子句。为了理解以上语法,让我们创建一个表。创建表的查询如下所示
mysql> create table NthSalaryDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Name varchar(10), -> Salary int, -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (1.03 sec)
使用insert命令在表中插入一些记录。查询如下所示
mysql> insert into NthSalaryDemo(Name,Salary) values('Larry',5700); Query OK, 1 row affected (0.41 sec) mysql> insert into NthSalaryDemo(Name,Salary) values('Sam',6000); Query OK, 1 row affected (0.16 sec) mysql> insert into NthSalaryDemo(Name,Salary) values('Mike',5800); Query OK, 1 row affected (0.16 sec) mysql> insert into NthSalaryDemo(Name,Salary) values('Carol',4500); Query OK, 1 row affected (0.17 sec) mysql> insert into NthSalaryDemo(Name,Salary) values('Bob',4900); Query OK, 1 row affected (0.20 sec) mysql> insert into NthSalaryDemo(Name,Salary) values('David',5400); Query OK, 1 row affected (0.27 sec) mysql> insert into NthSalaryDemo(Name,Salary) values('Maxwell',5300); Query OK, 1 row affected (0.21 sec) mysql> insert into NthSalaryDemo(Name,Salary) values('James',4000); Query OK, 1 row affected (0.19 sec) mysql> insert into NthSalaryDemo(Name,Salary) values('Robert',4600); Query OK, 1 row affected (0.19 sec)
使用select语句显示表中的所有记录。查询如下所示
mysql> select *from NthSalaryDemo;
以下是输出结果
+----+---------+--------+ | Id | Name | Salary | +----+---------+--------+ | 1 | Larry | 5700 | | 2 | Sam | 6000 | | 3 | Mike | 5800 | | 4 | Carol | 4500 | | 5 | Bob | 4900 | | 6 | David | 5400 | | 7 | Maxwell | 5300 | | 8 | James | 4000 | | 9 | Robert | 4600 | +----+---------+--------+ 9 rows in set (0.00 sec)
案例1:以下是获取列第n大值的查询。
以下查询将给出'Salary'列的第四大值
mysql> select *from NthSalaryDemo order by Salary desc limit 3,1;
以下是输出结果
+----+-------+--------+ | Id | Name | Salary | +----+-------+--------+ | 6 | David | 5400 | +----+-------+--------+ 1 row in set (0.00 sec)
案例2:以下是获取'Salary'列的第二大值的查询
mysql> select *from NthSalaryDemo order by Salary desc limit 1,1;
以下是输出结果
+----+------+--------+ | Id | Name | Salary | +----+------+--------+ | 3 | Mike | 5800 | +----+------+--------+ 1 row in set (0.00 sec)
案例3:以下是获取列的最大值的查询
mysql> select *from NthSalaryDemo order by Salary desc limit 1;
以下是输出结果
+----+------+--------+ | Id | Name | Salary | +----+------+--------+ | 2 | Sam | 6000 | +----+------+--------+ 1 row in set (0.00 sec)
案例4:如果要获取'Salary'列的第八大值,请使用以下查询
mysql> select *from NthSalaryDemo order by Salary desc limit 7,1;
以下是输出结果
+----+-------+--------+ | Id | Name | Salary | +----+-------+--------+ | 4 | Carol | 4500 | +----+-------+--------+ 1 row in set (0.00 sec)
广告