Mysql: seleccionar os valores máximos de topo n?

estou realmente confuso sobre a questão de que a necessidade de retornar as linhas N de topo tem os maiores valores na coluna particular.

por exemplo, se as linhas N-1, N, N + 1 tiverem os mesmos valores. Devo devolver just top N ou top N + 1 linhas.

Muito obrigado.

 18
Author: Hoa Vu, 2013-11-07

3 answers

Se o fizer:

select *
from t
order by value desc
limit N

Vais ficar com as linhas N superiores.

Se o fizer:

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;

Ou você poderia dizer isto um pouco mais simplesmente como:

select *
from t join
     (select value
      from t
      order by value
      limit N
    ) tlim
    on t.value = tlim.value;

O seguinte é conceptualmente o que você quer fazer, mas pode não funcionar em MySQL:

select *
from t
where t.value >= ANY (select value from t order by value limit N)
 24
Author: Gordon Linoff, 2013-11-07 03:29:22

Devias usar a auto-junção para isto.

  1. primeiro Encontre os valores superiores (n) possíveis para uma coluna perticular
  2. junta-te à mesma tabela com base na chave primária

Para, por exemplo, no quadro abaixo da amostra

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');

Com a tabela acima-dados configurados consulta para encontrar empregados com os 3 melhores salários seria:

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 

TIP:-

Se precisar do top 4, então mude LIMIT 3 paraLIMIT 4

 2
Author: Shirishkumar Bari, 2016-06-06 06:30:37

Utilize a seguinte consulta SQL.

SELECT salary FROM salesperson 
ORDER BY salary DESC
LIMIT 2,1
 2
Author: Tanmay S Mandalay, 2016-08-10 12:10:25