我对需要返回在特定列上具有最大值的前 N 行的查询感到非常困惑。
例如,如果行N-1, N, N + 1
具有相同的值。我必须返回just top N
还是top N + 1
行。
如果你这样做:
select *
from t
order by value desc
limit N
您将获得前 N 行。
如果你这样做:
select *
from t join
(select min(value) as cutoff
from (select value
from t
order by value
limit N
) tlim
) tlim
on t.value >= tlim;
或者您可以更简单地表述为:
select *
from t join
(select value
from t
order by value
limit N
) tlim
on t.value = tlim.value;
从概念上讲,以下是您想要做的事情,但它可能不适用于 MySQL:
select *
from t
where t.value >= ANY (select value from t order by value limit N)
使用以下 SQL 查询。
SELECT salary FROM salesperson
ORDER BY salary DESC
LIMIT 2,1
您应该为此使用自加入。
例如在下面的示例表中
CREATE TABLE `employee` (
`ID` INT(11) AUTO_INCREMENT PRIMARY KEY,
`NAME` VARCHAR(50) NOT NULL,
`SALARY` INT(11) NOT NULL ,
JOINING_DATE TIMESTAMP
) ENGINE=MYISAM
INSERT INTO employee (NAME,salary,joining_date) VALUES('JAMES',50000,'2010-02-02'),
('GARGI',60000,'2010-02-02'),('DAN',30000,'2010-02-02'),('JOHN',10000,'2010-02-02'),('MICHEL',70000,'2010-02-02'),
('STIEVE',50000,'2010-02-02'),('CALRK',20000,'2010-02-02'),('BINNY',50000,'2010-02-02'),('SMITH',40000,'2010-02-02'),
('ROBIN',60000,'2010-02-02'),('CRIS',80000,'2010-02-02');
使用上面的表数据设置查询以查找具有前 3 位薪水的员工 将是:
SELECT e1.* FROM
(SELECT DISTINCT salary FROM Employee ORDER BY salary DESC LIMIT 3 ) S1
JOIN employee e1
ON e1.salary = s1.salary
ORDER BY e1.salary DESC
小费:-
如果您需要前 4 名,则只需更改LIMIT 3
为LIMIT 4