美文网首页LeetCode
LeetCode SQL语句练习

LeetCode SQL语句练习

作者: Gpeko | 来源:发表于2019-01-19 21:50 被阅读0次

175. Combine Two Tables

1.left join

select p.FirstName, p.LastName, a.City, a.State from Person p LEFT JOIN Address a ON p.PersonId = a.PersonId

2.left join + using

select p.FirstName, p.LastName, a.City, a.State from Person p LEFT JOIN Address a using(PersonId)

3.natural left join

select p.FirstName, p.LastName, a.City, a.State from Person p NATURAL LEFT JOIN Address a

176. Second Highest Salary

使用max函数

select max(Salary) as SecondHighestSalary
from Employee
where Salary < (select max(Salary) from Employee) 

普通解法

select (
    select distinct Salary 
    from Employee 
    order by Salary desc 
    limit 1,1
) as SecondHighestSalary

MySQL 5 支持limit的另一种替代写法

select (
    select distinct Salary 
    from Employee 
    order by Salary desc 
    limit 1 offset 1
) as SecondHighestSalary

limit n offset m 表示从行m开始的n行数据,第一行数据为行0

需要注意的是

select distinct Salary as SecondHighestSalary 
from Employee 
order by Salary desc 
limit 1 offset 1

这种写法返回的是一个空值而不是NULL

177. Nth Highest Salary

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
  DECLARE M INT;
  SET M = N-1;
  RETURN (
      # Write your MySQL query statement below.\
      select distinct Salary
      from Employee
      order by Salary desc
      limit 1 offset M
  );
END

和上一个差不多的题,需要注意的是行是从0开始的,所以对于第N高的数据,其行值为N-1

相关文章

  • LeetCode SQL语句练习

    175. Combine Two Tables 1.left join 2.left join + using 3...

  • 2018-08-05--08-11

    08-05配置1、sql语句练习。根据月乔的文档&sql优化,根据文档练习2、hive语句1)hive,sql连接...

  • MySQL Operation

    sql语句练习sql练习2 MYSQL导入数据出现The MySQL server is running with...

  • LeetCode-SQL-nine

    Leetcode-sql-nine 本文中主要是介绍LeetCode中关于SQL的练习题,从易到难,循序渐进。文中...

  • LeetCode-SQL-five

    LeetCode-SQL-five 本文中主要是介绍LeetCode中关于SQL的练习题,从易到难,循序渐进。文中...

  • LeetCode-SQL-four

    LeetCode-SQL-four 本文中主要是介绍LeetCode中关于SQL的练习题,从易到难,循序渐进。文中...

  • MySQL 练习题

    01第一天20180703 【SQL练习】经典SQL练习题 02第二天20180704 sql语句练习50题(My...

  • SQL练习

    SQL练习-4张表 针对下面的4张表格进行SQL语句的练习。 image SQL练习-题目 查询001课程比002...

  • LeetCode-SQL-two

    LeetCode-SQL-two 本文中主要是介绍LeetCode中关于SQL的练习题,从易到难,循序渐进。文中会...

  • SQL语句练习

    一、已知有如下表,请用sql语句在mysql里建立相应的表 表1 学生表(student) 表2 课程表(cou...

网友评论

    本文标题:LeetCode SQL语句练习

    本文链接:https://www.haomeiwen.com/subject/ueqtjqtx.html