繁体   English   中英

这种方法在mysql的列中查找第二或第三或第四高值是否正确

[英]Is this method correct to find second or third or fourth highest value in a column in mysql

我在mysql中有表(名称为“ friend”),我想从该表中选择第二或第三或第四最高金额(即薪水)。

我正在使用这种方法:

`select * from friends order by salary desc limit 1; -- for highest salary.`

`select * from friends order by salary desc limit 1 offset 1; -- for second highest salary.`

`select * from friends order by salary desc limit 1 offset 2; -- for third highest salary.`

该方法正确吗?还是我必须使用其他逻辑方法?

`select * from friends where salary = (select max(salary) from friends where salary < (select max(salary) from friends)); -- for second highest salary`.

请告诉我这是专业方法。

具有偏移量的限制是首选,并且更合法。

select * 
from friends 
order by salary desc 
limit 3,1;

两种方法的区别在于时间复杂度

从一般意义上说,排序(或执行排序)仅看最高或次最高,这样在时间上就显得过头了。 考虑一下是否要在列表中找到最大的元素,是要对整个列表进行排序,然后对它进行排序后再查看第一个元素,还是在列表中循环查找最大的元素。

没有正确的方法,这取决于您是否有能力花更多的时间来找到解决方案,而要采用更具可读性的查询,这又取决于数据的大小等。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM