176. Second Highest Salary SQL查询语句中的 limit offset

题目:
Write a SQL query to get the second highest salary from the Employee table

  • Id | Salary
    ---|---
    1 | 100
    2 | 200
    3 | 300
For example, given the above Employee table, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null.
  • SecondHighestSalary
    200

Wrong answer: 只有一条记录时报错

SELECT DISTINCT
        Salary AS SecondHighestSalary
      FROM
        Employee
      ORDER BY Salary DESC
      LIMIT 1 OFFSET 1

answer1: 将Wrong answer的查询结果作为temp表

SELECT 
    (SELECT DISTINCT
        Salary
      FROM
        Employee
      ORDER BY Salary DESC
      LIMIT 1 OFFSET 1) AS SecondHighestSalary

answer2: Using IFNULL

SELECT 
    IFNULL(
        (SELECT DISTINCT 
            Salary
         FROM
            Employee
        ORDER BY Salary DESC
        LIMIT 1 OFFSET 1),
    NULL) AS SecondHighestSalary

相关知识点

SQL查询语句中的 limit offset

① selete * from testtable limit 2,1;

② selete * from testtable limit 2 offset 1;

注意:

1.数据库数据计算是从0开始的

2.offset X是跳过X个数据,limit Y是选取Y个数据

3.limit X,Y 中X表示跳过X个数据,读取Y个数据

这两个都是能完成需要,但是他们之间是有区别的:

①是从数据库中第三条开始查询,取一条数据,即第三条数据读取,一二条跳过

②是从数据库中的第二条数据开始查询两条数据,即第二条和第三条。

[1]SQL查询语句中的 limit offset

猜你喜欢

转载自www.cnblogs.com/TianchiLiu/p/9999503.html