我对需要返回特定列上前N行最大值的查询感到非常困惑。
例如,如果行 N-1, N, N + 1
具有相同的值。 我必须返回 仅前N行
还是 前N + 1
行。
我对需要返回特定列上前N行最大值的查询感到非常困惑。
例如,如果行 N-1, N, N + 1
具有相同的值。 我必须返回 仅前N行
还是 前N + 1
行。
select *
from t
order by value desc
limit 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;
select *
from t
where t.value >= ANY (select value from t order by value limit N)
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');
有了上面的表格数据设置,查找工资最高的前三名员工的查询将是:
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
提示:-
如果您需要前四个,则只需将LIMIT 3
更改为LIMIT 4