Leetcode_数据库

Leetcode_数据库

1、大的国家(595、Easy)

1)题目要求

这里有张 World 表

±----------------±-----------±-----------±-------------±--------------+
| name | continent | area | population | gdp |
±----------------±-----------±-----------±-------------±--------------+
| Afghanistan | Asia | 652230 | 25500100 | 20343000 |
| Albania | Europe | 28748 | 2831741 | 12960000 |
| Algeria | Africa | 2381741 | 37100000 | 188681000 |
| Andorra | Europe | 468 | 78115 | 3712000 |
| Angola | Africa | 1246700 | 20609294 | 100990000 |
±----------------±-----------±-----------±-------------±--------------+
如果一个国家的面积超过 300 万平方公里,或者人口超过 2500 万,那么这个国家就是大国家。

编写一个 SQL 查询,输出表中所有大国家的名称、人口和面积。

例如,根据上表,我们应该输出:

±-------------±------------±-------------+
| name | population | area |
±-------------±------------±-------------+
| Afghanistan | 25500100 | 652230 |
| Algeria | 37100000 | 2381741 |
±-------------±------------±-------------+

2)我的解法

select name,population,area 
from World 
where area>3000000 or population>25000000

3)其他解法

select name,population,area 
from World 
where area>3000000 
union
select name,population,area 
from World 
where population>25000000

作者:LeetCode
链接:link
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

在这里插入图片描述

stackoverflow链接:

4)自己的优化代码

select name,population,area 
from World 
where area>3000000 
union
select name,population,area 
from World 
where population>25000000

5)学到的东西

union两个索引都能用上,但会自动排序去重,会影响效率

2、变更性别(627、Easy)

1)题目要求

给定一个 salary 表,如下所示,有 m = 男性 和 f = 女性 的值。交换所有的 f 和 m 值(例如,将所有 f 值更改为 m,反之亦然)。要求只使用一个更新(Update)语句,并且没有中间的临时表。

注意,您必只能写一个 Update 语句,请不要编写任何 Select 语句。

例如:

idnamesexsalary
1Am2500
2Bf1500
3Cm5500
4Df500

运行你所编写的更新语句之后,将会得到以下表:

idnamesexsalary
1Af2500
2Bm1500
3Cf5500
4Dm500

2)我的解法

1、IF函数

update salary
set sex=IF(sex='f','m','f')

2、if else

update salary
set sex= 
case when sex='m' then 'f'
else 'm' end

3、switch case

update salary
set sex= 
case sex when 'm' then 'f'
else 'm' end

3)其他解法

1、

UPDATE salary
SET
    sex = CASE sex
        WHEN 'm' THEN 'f'
        ELSE 'm'
    END;

作者:LeetCode
链接: link
来源:力扣(LeetCode)
2、

update salary 
set sex = char(ascii('m') + ascii('f') - ascii(sex));

4)自己的优化代码

update salary
set sex= case sex 
            when 'm' then 'f'
            else 'm' 
        end

5)学到的东西

函数用法
IF(value,t ,f)如果value是真,返回t,否则返回f
IFNULL(value1, value2)如果value1不为空,返回value1,否则返回value2
CASE WHEN 条件1 THEN result1 WHEN 条件2 THEN result2 … [ELSE resultn] END相当于Java的if…else if…else…
CASE expr WHEN 常量值1 THEN 值1 WHEN 常量值1 THEN 值1 … [ELSE 值n] END相当于Java的switch…case…

3、有趣的电影(620、Easy)

1)题目要求

某城市开了一家新的电影院,吸引了很多人过来看电影。该电影院特别注意用户体验,专门有个 LED显示板做电影推荐,上面公布着影评和相关电影描述。

作为该电影院的信息部主管,您需要编写一个 SQL查询,找出所有影片描述为非 boring (不无聊) 的并且 id 为奇数 的影片,结果请按等级 rating 排列。

例如,下表 cinema:

±--------±----------±-------------±----------+
| id | movie | description | rating |
±--------±----------±-------------±----------+
| 1 | War | great 3D | 8.9 |
| 2 | Science | fiction | 8.5 |
| 3 | irish | boring | 6.2 |
| 4 | Ice song | Fantacy | 8.6 |
| 5 | House card| Interesting| 9.1 |
±--------±----------±-------------±----------+
对于上面的例子,则正确的输出是为:

±--------±----------±-------------±----------+
| id | movie | description | rating |
±--------±----------±-------------±----------+
| 5 | House card| Interesting| 9.1 |
| 1 | War | great 3D | 8.9 |
±--------±----------±-------------±----------+

2)我的解法

select *
from cinema 
where description!='boring' and id%2=1
order by rating desc

3)其他解法

select *
from cinema
where mod(id, 2) = 1 and description != 'boring'
order by rating DESC
;

作者:LeetCode
链接:link
来源:力扣(LeetCode)

4)自己的优化代码

select *
from cinema 
where description<>'boring' and mod(id,2)=1
order by rating desc

5)学到的东西

mod(x,y)返回x/y的模
!=与<>等价

4、超过5名学生的课(596、Easy)

1)题目要求

有一个courses 表 ,有: student (学生) 和 class (课程)。

请列出所有超过或等于5名学生的课。

例如,表:

±--------±-----------+
| student | class |
±--------±-----------+
| A | Math |
| B | English |
| C | Math |
| D | Biology |
| E | Math |
| F | Computer |
| G | Math |
| H | Math |
| I | Math |
±--------±-----------+
应该输出:

±--------+
| class |
±--------+
| Math |
±--------+

提示:

学生在每个课中不应被重复计算。

2)我的解法

select class 
from courses
group by class 
having count(distinct student)>=5

3)其他解法

在这里插入图片描述

SELECT
    class
FROM
    (SELECT
        class, COUNT(DISTINCT student) AS num
    FROM
        courses
    GROUP BY class) AS temp_table
WHERE
    num >= 5
;

作者:LeetCode
链接:link
来源:力扣(LeetCode)

4)自己的优化代码

select class 
from courses
group by class 
having count(distinct student)>=5

5)学到的东西

distinct

group by
having

5、查找重复的电子邮箱(182、Easy)

1)题目要求

编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。

示例:

±—±--------+
| Id | Email |
±—±--------+
| 1 | a@b.com |
| 2 | c@d.com |
| 3 | a@b.com |
±—±--------+
根据以上输入,你的查询应返回以下结果:

±--------+
| Email |
±--------+
| a@b.com |
±--------+
说明:所有电子邮箱都是小写字母。

2)我的解法

select Email 
from Person 
group by Email
having count(*)>1

3)其他解法

select Email from
(
  select Email, count(Email) as num
  from Person
  group by Email
) as statistic
where num > 1
;

作者:LeetCode
链接:link
来源:力扣(LeetCode)

4)自己的优化代码

select Email 
from Person 
group by Email
having count(*)>1

5)学到的东西

group by

6、删除重复的电子邮箱(196、Easy)

1)题目要求

编写一个 SQL 查询,来删除 Person 表中所有重复的电子邮箱,重复的邮箱里只保留 Id 最小 的那个。

±—±-----------------+
| Id | Email |
±—±-----------------+
| 1 | john@example.com |
| 2 | bob@example.com |
| 3 | john@example.com |
±—±-----------------+
Id 是这个表的主键。
例如,在运行你的查询语句之后,上面的 Person 表应返回以下几行:

±—±-----------------+
| Id | Email |
±—±-----------------+
| 1 | john@example.com |
| 2 | bob@example.com |
±—±-----------------+

提示:

执行 SQL 之后,输出是整个 Person 表。
使用 delete 语句。

2)我的解法

不会

3)其他解法

DELETE p1 FROM Person p1,
    Person p2
WHERE
    p1.Email = p2.Email AND p1.Id > p2.Id

作者:LeetCode
链接:link
来源:力扣(LeetCode)

4)自己的优化代码

delete p1
from Person p1,Person p2
where p1.id>p2.id and p1.Email=p2.Email

5)学到的东西

自己连接自己

如果用了表别名,delete后要加别名

7、 组合两个表(175、Easy)

1)题目要求

表1: Person

±------------±--------+
| 列名 | 类型 |
±------------±--------+
| PersonId | int |
| FirstName | varchar |
| LastName | varchar |
±------------±--------+
PersonId 是上表主键
表2: Address

±------------±--------+
| 列名 | 类型 |
±------------±--------+
| AddressId | int |
| PersonId | int |
| City | varchar |
| State | varchar |
±------------±--------+
AddressId 是上表主键

编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:

FirstName, LastName, City, State

2)我的解法

select p.FirstName,p.LastName,a.City,a.State
from Person p left join Address a
on p.PersonId=a.PersonId

3)其他解法

一样

4)自己的优化代码

select p.FirstName,p.LastName,a.City,a.State
from Person p left join Address a
on p.PersonId=a.PersonId

5)学到的东西

left join

8、超过经理收入的员工(181、Easy)

1)题目要求

Employee 表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。

±—±------±-------±----------+
| Id | Name | Salary | ManagerId |
±—±------±-------±----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
±—±------±-------±----------+
给定 Employee 表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。

±---------+
| Employee |
±---------+
| Joe |
±---------+

2)我的解法

select e.name Employee
from Employee e,Employee m
where e.Salary>m.Salary and e.ManagerId=m.Id

3)其他解法

SELECT
     a.NAME AS Employee
FROM Employee AS a JOIN Employee AS b
     ON a.ManagerId = b.Id
     AND a.Salary > b.Salary
;

作者:LeetCode
链接: link
来源:力扣(LeetCode)

4)自己的优化代码

select e.name as Employee
from Employee as e,Employee as m
where e.Salary>m.Salary and e.ManagerId=m.Id

5)学到的东西

Employee e或Employee as e起别名
自连接

9、从不订购的客户(183、Easy)

1)题目要求

某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。

Customers 表:

±—±------+
| Id | Name |
±—±------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
±—±------+
Orders 表:

±—±-----------+
| Id | CustomerId |
±—±-----------+
| 1 | 3 |
| 2 | 1 |
±—±-----------+
例如给定上述表格,你的查询应返回:

±----------+
| Customers |
±----------+
| Henry |
| Max |
±----------+

2)我的解法

select c.Name as Customers
from Customers c left join Orders o
on c.Id=o.CustomerId 
where o.CustomerId is null

3)其他解法

select customers.name as 'Customers'
from customers
where customers.id not in
(
    select customerid from orders
);

作者:LeetCode
链接: link
来源:力扣(LeetCode)

4)自己的优化代码

select c.Name as Customers
from Customers c left join Orders o
on c.Id=o.CustomerId 
where o.CustomerId is null

5)学到的东西

在这里插入图片描述

10、部门工资最高的员工(184、Easy)

1)题目要求

Employee 表包含所有员工信息,每个员工有其对应的 Id, salary 和 department Id。

±—±------±-------±-------------+
| Id | Name | Salary | DepartmentId |
±—±------±-------±-------------+
| 1 | Joe | 70000 | 1 |
| 2 | Jim | 90000 | 1 |
| 3 | Henry | 80000 | 2 |
| 4 | Sam | 60000 | 2 |
| 5 | Max | 90000 | 1 |
±—±------±-------±-------------+
Department 表包含公司所有部门的信息。

±—±---------+
| Id | Name |
±—±---------+
| 1 | IT |
| 2 | Sales |
±—±---------+
编写一个 SQL 查询,找出每个部门工资最高的员工。对于上述表,您的 SQL 查询应返回以下行(行的顺序无关紧要)。

±-----------±---------±-------+
| Department | Employee | Salary |
±-----------±---------±-------+
| IT | Max | 90000 |
| IT | Jim | 90000 |
| Sales | Henry | 80000 |
±-----------±---------±-------+
解释:

Max 和 Jim 在 IT 部门的工资都是最高的,Henry 在销售部的工资最高。

2)我的解法

select d.name as Department,e.name as Employee ,e.Salary
from Department d inner join Employee e
on e.DepartmentId=d.Id
where e.Salary in(
    select max(Salary) 
    from Employee
    group by DepartmentId
    having Employee.DepartmentId=e.DepartmentId
)

3)其他解法

在这里插入图片描述

SELECT
    Department.name AS 'Department',
    Employee.name AS 'Employee',
    Salary
FROM
    Employee
        JOIN
    Department ON Employee.DepartmentId = Department.Id
WHERE
    (Employee.DepartmentId , Salary) IN
    (   SELECT
            DepartmentId, MAX(Salary)
        FROM
            Employee
        GROUP BY DepartmentId
	)
;

作者:LeetCode
链接:link
来源:力扣(LeetCode)

4)自己的优化代码

select d.name as Department,e.name as Employee ,e.Salary
from Department d inner join Employee e
on e.DepartmentId=d.Id
where e.Salary =(
    select max(Salary) 
    from Employee
    group by DepartmentId
    having Employee.DepartmentId=e.DepartmentId
)

5)学到的东西

in

11、第二高的薪水(11、Easy)

1)题目要求

编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。

±—±-------+
| Id | Salary |
±—±-------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
±—±-------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。

±--------------------+
| SecondHighestSalary |
±--------------------+
| 200 |
±--------------------+

2)我的解法

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

3)其他解法

1、

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

2、

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

作者:LeetCode
链接:link
来源:力扣(LeetCode)

4)自己的优化代码

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

5)学到的东西

IFNULL(value1, value2) 如果value1不为空,返回value1,否则返回value2

limit 1,1与limit 1 offset 1:
【MySQL】LIMIT以及LIMIT OFFSET

12、第N高的薪水(177、Medium)

1)题目要求

编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。

±—±-------+
| Id | Salary |
±—±-------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
±—±-------+
例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 n 高的薪水,那么查询应返回 null。

±-----------------------+
| getNthHighestSalary(2) |
±-----------------------+
| 200 |
±-----------------------+

2)我的解法

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
    set N:=N-1;
  RETURN (
      # Write your MySQL query statement below.
      select 
        IFNULL(
            (select distinct Salary
            from Employee
            order by Salary desc
            limit N,1),null
        )
  );
END

3)其他解法

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
    DECLARE P1 INT; -- 第P1高的薪水
    DECLARE P2 INT; -- 取P1-1后的P2个值
    -- 当N<1时,P1会为负数,采用IF调整为0,另此时结果不存在,设置P2为0
    IF (N<1)
      THEN SET P1 = 0, P2 = 0;
    ELSE SET P1 = N-1, P2 = 1;
    END IF;
    
    RETURN (
        -- 若不存在第N高的薪水,取NULL
        SELECT IFNULL(
            (
                -- 去除重复值,倒序取第P1大的值后P2个值
               SELECT DISTINCT Salary
                FROM Employee
                ORDER BY Salary DESC
                LIMIT P1, P2
            ), NULL
        ) AS SecondHighestSalary   
    );
END

作者:cibo
链接:link
来源:力扣(LeetCode)

4)自己的优化代码

CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
    set N:=N-1;
  RETURN (
      # Write your MySQL query statement below.
      select 
        IFNULL(
            (select distinct Salary
            from Employee
            order by Salary desc
            limit N,1),null
        )
  );
END

5)学到的东西

set N:N-1;

DECLARE P INT DEFAULT N-1;

13、分数排名(78、Medium)

1)题目要求

编写一个 SQL 查询来实现分数排名。

如果两个分数相同,则两个分数排名(Rank)相同。请注意,平分后的下一个名次应该是下一个连续的整数值。换句话说,名次之间不应该有“间隔”。

±—±------+
| Id | Score |
±—±------+
| 1 | 3.50 |
| 2 | 3.65 |
| 3 | 4.00 |
| 4 | 3.85 |
| 5 | 4.00 |
| 6 | 3.65 |
±—±------+
例如,根据上述给定的 Scores 表,你的查询应该返回(按分数从高到低排列):

±------±-----+
| Score | Rank |
±------±-----+
| 4.00 | 1 |
| 4.00 | 1 |
| 3.85 | 2 |
| 3.65 | 3 |
| 3.65 | 3 |
| 3.50 | 4 |
±------±-----+
重要提示:对于 MySQL 解决方案,如果要转义用作列名的保留字,可以在关键字之前和之后使用撇号。例如 Rank

2)我的解法

不会

3)其他解法

在这里插入图片描述

select a.Score as Score,
(select count(distinct b.Score) from Scores b where b.Score >= a.Score) as Rank
from Scores a
order by a.Score DESC

作者:johnbear007
链接:link
来源:力扣(LeetCode)

4)自己的优化代码

select a.Score as'Score' ,
(
    select count(distinct b.Score)
    from Scores b
    where b.Score>=a.Score 
)as 'Rank'
from Scores a
order by a.Score desc

5)学到的东西

给你一个分数X,如何算出它的排名Rank:

我们可以先提取出大于等于X的所有分数集合H,将H去重后的元素个数就是X的排名。比如你考了99分,但最高的就只有99分,那么去重之后集合H里就只有99一个元素,个数为1,因此你的Rank为1。
先提取集合H:

14、 连续出现的数字(180、Medium)

1)题目要求

编写一个 SQL 查询,查找所有至少连续出现三次的数字。

±—±----+
| Id | Num |
±—±----+
| 1 | 1 |
| 2 | 1 |
| 3 | 1 |
| 4 | 2 |
| 5 | 1 |
| 6 | 2 |
| 7 | 2 |
±—±----+
例如,给定上面的 Logs 表, 1 是唯一连续出现至少三次的数字。

±----------------+
| ConsecutiveNums |
±----------------+
| 1 |
±----------------+

2)我的解法

不会

3)其他解法

SELECT DISTINCT
    l1.Num AS ConsecutiveNums
FROM
    Logs l1,
    Logs l2,
    Logs l3
WHERE
    l1.Id = l2.Id - 1
    AND l2.Id = l3.Id - 1
    AND l1.Num = l2.Num
    AND l2.Num = l3.Num
;

作者:LeetCode
链接:link
来源:力扣(LeetCode)

4)自己的优化代码

select distinct l1.Num as ConsecutiveNums
from Logs l1,Logs l2,Logs l3
where l1.Num=l2.Num and l2.num=l3.num
    and l2.Id=l1.Id+1 and l3.Id=l2.Id+1

5)学到的东西

自连接

15、换座位(626、Medium)

1)题目要求

小美是一所中学的信息科技老师,她有一张 seat 座位表,平时用来储存学生名字和与他们相对应的座位 id。

其中纵列的 id 是连续递增的

小美想改变相邻俩学生的座位。

你能不能帮她写一个 SQL query 来输出小美想要的结果呢?

示例:

±--------±--------+
| id | student |
±--------±--------+
| 1 | Abbot |
| 2 | Doris |
| 3 | Emerson |
| 4 | Green |
| 5 | Jeames |
±--------±--------+
假如数据输入的是上表,则输出结果如下:

±--------±--------+
| id | student |
±--------±--------+
| 1 | Doris |
| 2 | Abbot |
| 3 | Green |
| 4 | Emerson |
| 5 | Jeames |
±--------±--------+
注意:

如果学生人数是奇数,则不需要改变最后一个同学的座位。

2)我的解法

不会

3)其他解法

在这里插入图片描述

select 
    if(id%2=0,
        id-1,
        if(id=(select count(distinct id) from seat),
            id,
            id+1)) 
    as id,student 
from seat 
order by id;

作者:fan-lu-5
链接: link
来源:力扣(LeetCode)

4)自己的优化代码

select if(id%2=0,
        id-1,
            if(id=(select count(*)from seat),
                id,
                id+1
                )
        )as id,student
from seat
order by id

5)学到的东西

if()函数

偶数-1,奇数+1,最后那个不变

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值