选择第5个最高值而不使用LIMIT

时间:2012-05-08 08:52:54

标签: mysql sql

我是SQL新手,我想在不使用LIMIT的情况下获取第5个最高值。这是我正在尝试的代码,但它无法正常工作。它显示的是第5个最低值而不是第5个最高值。

SELECT a . * FROM user AS a 
WHERE 5 = 
(SELECT count( DISTINCT b.id ) FROM user  AS b WHERE b.id >= a.id ORDER BY a.id DESC)

任何人都可以帮我吗?

3 个答案:

答案 0 :(得分:4)

你也可以这样做:

SET @nth := 5;
SELECT
    a.*
FROM jos_modules AS a
WHERE  @nth = ( 
    SELECT 
        COUNT(b.id) 
    FROM user AS b
    WHERE 
        a.id >= b.id
);

答案 1 :(得分:0)

试试这个

SELECT a . *
FROM user AS a
WHERE 5 = (
SELECT count( DISTINCT b.id )
FROM user AS b
WHERE a.id >= b.id ORDER BY a.id )

答案 2 :(得分:0)

select * from (
select a.* , row_number() over (order by id asc) as RANK
from a ) where RANK=5 ;

如果您使用的是Teradata数据库,则可以使用限定语句:

select * from a 
qualify row_number () over(order by id asc)=5;