从包含三列Id,名称,工资的表中查找第二高薪

时间:2014-03-21 08:43:44

标签: mysql

如何从包含三列的表中找到第二高薪,这些列是 id name {{1 } 但在 salary 中使用。通过 SELF JOIN 进行回答。但是,我想知道如何使用 nested query

进行框架处理

3 个答案:

答案 0 :(得分:0)

为什么只能使用SELECT语句进行连接?

试试这个:

SELECT DISTINCT salary FROM myTable ORDER BY salary DESC LIMIT 1,1 ;

答案 1 :(得分:0)

如果你必须使用自我加入,你可以做这样的事情......

SELECT x.val 
  FROM my_table x 
  JOIN my_table y 
    ON y.val >= x.val 
 GROUP 
    BY x.val HAVING COUNT(DISTINCT y.val) = ?

答案 2 :(得分:0)

从包含三个颜色ID,名称,工资的表中查找第二高薪:

SELECT id,NAME,salary FROM high
WHERE salary = (SELECT DISTINCT(salary) FROM high AS e1
WHERE (SELECT COUNT(DISTINCT(salary))=2 FROM high AS e2
WHERE e1.salary <=e2.salary))
ORDER BY NAME;

查看sqlfiddle

anthor一个有趣的答案:

SELECT id,NAME,salary
FROM high 
WHERE salary = (SELECT DISTINCT(salary) 
                FROM high AS e1 
                WHERE id  = (SELECT COUNT(DISTINCT(salary)) 
                             FROM high AS e2 
                             WHERE e1.salary <= e2.salary))